Ramon Larodo
Ramon Larodo

Reputation: 95

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

Upvotes: 3

Views: 2545

Answers (3)

Christophe
Christophe

Reputation: 73446

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

Upvotes: 2

e.proydakov
e.proydakov

Reputation: 602

In parent. Use

system("child_application my arg list");

In child. Use

int main(int argc, char *argv[])

For easy parsing args try boost program_options library.

In unix system can use fork. Child process get all parent memory.

Upvotes: 0

mrflash818
mrflash818

Reputation: 934

If fork() is used, then the child process inherits from the parent process.

http://man7.org/linux/man-pages/man2/fork.2.html

If you mean just passing variables between instances of objects in memory, then you'd create variables for int argc and char * argv[] to pass along.

Upvotes: 0

Related Questions