Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to pass command line args between processes?

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

like image 374
Ramon Larodo Avatar asked Jun 09 '26 13:06

Ramon Larodo


1 Answers

#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:

  • replace the calling process (as exec in posix)
  • create a new process and keep the calling one (as fork/exec combination above)
  • or even if you want to suspend the calling process until the child process finished.
like image 120
Christophe Avatar answered Jun 11 '26 21:06

Christophe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!