how to correctly use fork, exec, wait

Here’s a simple, readable solution:

pid_t parent = getpid();
pid_t pid = fork();

if (pid == -1)
{
    // error, failed to fork()
} 
else if (pid > 0)
{
    int status;
    waitpid(pid, &status, 0);
}
else 
{
    // we are the child
    execve(...);
    _exit(EXIT_FAILURE);   // exec never returns
}

The child can use the stored value parent if it needs to know the parent’s PID (though I don’t in this example). The parent simply waits for the child to finish. Effectively, the child runs “synchronously” inside the parent, and there is no parallelism. The parent can query status to see in what manner the child exited (successfully, unsuccessfully, or with a signal).

Leave a Comment