I have a parent process that needs to send it is command line args to the its child? How I can do this? I mean from parent.cpp to child .cpp? Thanks
#POSIX (Linux) solution:
Use execvp(const char *file, char *const argv[]) to run a programme with arguments in place of the current programme. The argv[] that you pass as reference, follows the same logic as the argv[] parameter passing in main().
If you want to keep your current process running and launch the new programme in a distinct process, then you have to first fork(). The rough idea is something like:
pid_t pid = fork(); // creates a second process, an exact copy of the current one
if (pid==0) { // this is exectued in the child process
char **argv[3]{".\child","param1", NULL };
if (execvp(argv[0], argv)) // execvp() returns only if lauch failed
cout << "Couldn't run "<<argv[0]<<endl;
}
else { // this is executed in the parent process
if (pid==-1) //oops ! This can hapen as well :-/
cout << "Process launch failed";
else cout << "I launched process "<<pid<<endl;
}
#Windows solution
The easiest windows alternative is to use the ms specific _spawnvp() or similar functions. It takes same arguments as the exec version, and the first parameters tells if you want to:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With