Main function for a child process - c++

I have a small but confusing problem...
First question is what is the use of main.I know the question is silly and simple but i have a problem.I have written a code
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
int main(){
pid_t ty;
ty=fork();
if(ty==0){
const char* x="/home/brucewilson/Desktop/jack_sahoo_teja_CDP/hey2";
static char *argv[]={"echo","Foo is my name.",NULL};
int main(){//observe this is second main in my child process
printf("hello");
}
int add(){
printf("5");
}
main();
add();
}
}`
Did you observe the second main function i used in my child process well the compiler gave me no error for this..Added to this it gave me the output as "hello" and 5.
And obviously the below code would give an error...
int main(){
printf("main");
main();
}
int main(){
}
So my question is why did it work for the child process?So is the notion that im assuming to be true that is no function can be named main() and every child process will have a main function shared from its parent is false.Please explain me what is going underneath this code inside my system because the child process assumes main just as another function and it doesnot need a main function also.Then how will the child process know from where should it start?

You are using a non-standard GCC extension known as 'nested functions'.
You second example fails because you aren't nesting the second definition of main() so it conflicts with the first one.

Related

Terminate called without an active exception when returning from a method

I am making this game and i need to return back to the main method again to start another life of the player. but when i am returning from the method of another class the error comes as terminate called without an active exception.
I have tried looking how to close the thread before returning but most of the solutions i find on internet they just close all the threads including main and so no work i just want to return to the main method. I have replicated my problem in the following code. I think there is a very simple answer to this that i am not able to figure out so please help me out.
#include<iostream>
#include<conio.h>
#include<thread>
using namespace std;
class first{
public:
int ch;
void getDir();
void func();
};
void first::getDir(){
while(1){
ch = _getch();
}
}
void first::func(){
thread getDirection(&first::getDir,this);
while(1){
//do stuff
while(1){
//do stuff
return;
}
}
}
int main(){
while(1){
first f;
f.func();
}
}

Parallelizing C-Code Module in C++ Program

My situation:
I have C code running on a microcontroller. To test this code I have written a test program in C++ that checks the C-functions. Since the test functions are very slow, I wanted to do the whole thing in parallel. However, I don't have much experience.
For example, I have a program module in C that looks like this:
/* c-code: */
static int a=0;
void set_a(int value){
a = value;
}
void inc_a(void){
a++;
}
int get_a(void){
return a;
}
Now I want to parallelize these functions in C++. However, I am bothered by the global variable a, which cannot be avoided in my situation.
In the QT environment I want to perform an "asynchronous run" of the function inc_a. This works but does not improve:
int foo(int somevalue){
set_a(somevalue);
inc_a();
return get_a();
}
int myinput = 1,myoutput;
QFuture<int> future = QtConcurrent::run(foo,myinput);
future.waitForFinished();
myoutput = future.result();
This is what I want:
int myinput1 = 1,myoutput1;
int myinput2 = 8,myoutput2;
QFuture<int> future1 = QtConcurrent::run(foo,myinput1);
QFuture<int> future2 = QtConcurrent::run(foo,myinput2);
future1.waitForFinished();
future2.waitForFinished();
myoutput1 = future1.result();
myoutput2 = future2.result();
So my first question is (to be sure): is it correct that the variable a (in C) is now the same in both threads? If not, I have to look over my code again.If yes, how do I solve the problem as elegantly as possible? I thought of creating two C-program modules with the same functionality. However, this makes the program very maintenance-unfriendly:
/* c-code: */
static int a1=0;
void set_a1(int value){
a1 = value;
}
void inc_a1(void){
a1++;
}
int get_a1(void){
return a1;
}
static int a2=0;
void set_a2(int value){
a2 = value;
}
void inc_a2(void){
a2++;
}
int get_a2(void){
return a2;
}
Is there a better way?
You are out of luck.
Ideally, rewrite your testable asset so that it carries round a state struct containing all those pesky globals, and maybe you will get away with it.
Vroomfondel also suggests that wrapping the offending C code in a namespace might hide the issue, if the code can be made to compile as C++.
You could create as many namespaces as you want parallel threads:
namespace TEST1
{
#include "offender.c"
}
namespace TEST2
{
#include "offender.c"
}
RetCode DoTest(int instance, TestId testid)
{
switch (instance)
{
case 1: return TEST1::DoTest(testid);
case 2: return TEST2::DoTest(testid);
}
return OUT_OF_RANGE;
}
If your target really uses global state and can't be changed, then you could consider using forks.
In a fork, a complete copy of the current state is made for the child to run in, and they both resume with just enough info so you know which is the child and which is the owner. You can also set up a pipe for them to communicate with each other. When a test completes, it transmits its status and exits its forked process.
Forks can be really good for test suites because each fork starts with a completely clean environment.
There is a /lot/ more to getting forking right than I think is reasonable to put as an answer to this question.
The third option is to drive the program externally, so that some monitor script or program launches multiple parallel instances that each run linearly through a subset of the test list. Ideally build in features so the monitor can dispatch tests on demand and load-balance.

Is there possibility to invoke other methods/instructions AFTER main() when running the code

Is there any possibility to run any other instructions after int main() is invoked?
int main(){cout<<"a";}
and after that call in main() there is call for cout<<"b"; somewhere after. No change int main()whatsoever.
Destructors of static objects, and functions registered with std::atexit, are executed after main exits.
#include <iostream>
#include <cstdlib>
struct S {~S() {std::cout << "c";}};
void f() {std::cout << "b";}
S s;
int main() {
std::atexit(f);
std::cout << "a";
}
Output: abc
You could put your last part in atexit().
It will run on program termination, i.e. after your call to main() is completed.
You could have multiple atexits as well.
If more than one atexit function has been specified by different calls
to this function, they are all executed in reverse order as a stack
(i.e. the last function specified is the first to be executed at
exit).
Yes, define a class that does cout << "b" in its destructor, and then define a global instance of that class.
In short, very little option. You can use atexit() to make something happen after main exits, or you can have a global object whose destructor is called after main exits. But the end of main is officially the end of your program.

how to execute a particular code in c++ after every 1 minute

I need to make something(i call it a scheduler) that checks the time of the sytem every minute and if the time has changed suppose it is 17:52 and the next moment it is 17:53so at 17:53 it calls a function logupdated
How do i make this simply i m not known to the mutex and all.
Thanks
I am not sure I understand the requirements, but your question reads "how to execute a particular code in c++ after every 1 minute", so, in c++11 you can do this:
#include <thread>
#include <chrono>
int main() {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(60));
// call your c++ code
}
}
If you want the execution of the task to be independent of the main program flow, consider multithreading.
this example in C, should work also on C++
Note that some people think that I use pointers excessively, I agree, specially with multithreading, it can cause unsafe threads, thus data corruption or even worse, segmentation faults.
However this is the only way to pass arguments to threads as far as I could find.
#include <pthread.h>
int main(int argc, char *argv[]) {
pthread_t thread1;
int variables=10;
pthread_create( &thread1, NULL, scheduler, (void*)&variables);
while(1){
.... do stuff as main program.
}
return 0;
}
void *scheduler (void* variables) {
int vars;
int* p_vars = (int*) variables;
vars = *p_vars;
while (1){
.. do scheduler stuff
sleep (vars);
}
}

Persistent storage across several runs

I was wondering what would be the best solution for having a storage container that does not loose its contents over several execution times (runs) without using input-output to the filesystem or external database.
Say I have a class foo() which stores integers. From main() I want to call a method that adds an integer and the class does not forget about its former contents.
//
// Data storage accross different runs
// This should go into the daemon process
//
#include<iostream>
#include<list>
using namespace std;
class foo {
public:
foo(int add): add(add) {}
void store(int i) {
vec.push_back( i + add);
}
private:
list<int> vec;
int add;
};
The main function should check for an already running daemon - if not starts it.
//
// Main program. Should check whether daemon runs already, if not starts it.
//
void main(int argc, char *argv[]) {
// if (daemon is not running)
// start daemon( some_number )
// call daemon::add( atoi(argv[1]) );
}
How would one do this best with shared libraries or with a daemon process? Storage and caller program are on the same Linux host.
Look at Linux Pipes for interprocess communication.
http://linux.die.net/man/2/pipe
Named pipes is one way. If you want non blocking though you might want to try the message queue route. Here is a link to one of the system calls http://linux.die.net/man/2/msgctl, you can look at the other calls from there.
May consider http://en.wikipedia.org/wiki/Memcached