Unix: fork and wait Unix: fork and wait shell shell

Unix: fork and wait


fork splits the current process in two: it makes a new process, running the same code, which begins running from the same point as the fork call. fork returns a different value in the parent and the child: in the parent, it returns the PID of the child process, and in the child it returns zero. The PID is a true value, so the wait call only executes in the parent (as the comment says), and the "else" branch only executes in the child (as its comment says). Both processes execute in parallel from the point of the fork onwards.

doex performs an exec of another program, replacing the child process and terminating with the new process's exit code. Only the doex call and execv execute in the child process from the current program.

wait:

causes its caller to delay until one of its child processes terminates.

That is, it causes the parent to pause until the child has exited. It is passed a pointer to an int variable and writes exit information for the child process into that variable. ccode is defined elsewhere in the enclosing function. The child process's exit code will be the exit code of the command that was execed.

When ccode has been given a non-zero value, that indicates an error running the program. In that case, the function returns zero, and otherwise it returns 1 to indicate success to its caller.


I encourage you take a look at either POSIX/the Single Unix Specification, the ISO C standard, or a standard C programming textbook to help understand what's going on in this codebase. The man pages that you link to also describe what the functions do, but often the newer versions fill in the gaps or are generally clearer, and the behaviour hasn't changed too much.

Although all of these questions are related to historical Unix, and the interplay between Unix and C at that point combined with the subsequent changes to both in the intervening time makes them arguably on-topic, they're also rudimentary programming questions (and so arguably off-topic).