int main()
{
...
if(!fork())
{
execvp(cmdName,cmdParam);
}
printf("In main()...");
return(0);
}
- Assuming I have correctly passed the cmdName & cmdParam arguments, how do I wait for the process created by execvp to finish, before resuming the execution of main()?
- Does the execvp() create a process which is a child of the newly fork()ed process?
In the parent process,
fork
returns the PID of the child process, so you can store that in a variable, and then usewaitpid
to wait for the child process to terminate.Not really - the new child process created by
fork
is a duplicate of the parent, andexecvp
then replaces its process image with a new image. Effectively you initially have two 'copies' of the parent, one of which then 'becomes' the new program.For your first question:
Use waitpid(2) like this:
For the second part: all exec function calls take the process over (none of them return)
As noted you need to save the value of the fork call. You should really use more than an if on the fork. There are three cases:
You really want to know about case 3, it'll ruin your whole day. (also the exec call)
return(0); }
You need to store the return value of
fork()
, which returns a different value to each executable (0 if you are the child PID if you are the parent), and then you need to do awaitpid