Illustration courtesy of Roz Cyrus.
forkreally is (full program is also online right here).
printfgets executed twice. The child is always the first to execute it, because the parent is blocked in its
waitpidcall until the child executes in full.
forkmultiple times, provided it reaps the child processes (via
waitpid) once they exit. Note that we reap processes as they exit without worrying about the order they were spawned! Full program is also online right here.
waitpid. The -1 means want to hear about any child as it exits, so that pids are returned in the order their processes finish.
waitpidreturns -1, it sets a global variable called
errnoto the constant
waitpidreturned -1 because all child processes have terminated. That's the "error" we want.
cplayground: The OS looks to randomly schedule child processes, allowing them to complete and be reaped in a somewhat unpredictable order.
myth: The OS appears to be fairly regimented and round-robin in how it selects child processes to run. I ran reap-as-they-exit some 100 times and always got this output.
Below is a sample run of the reap-in-fork-order executable. The pids change between runs, of course, but even those are guaranteed to be published in increasing order.
execvp system call!
execvp effectively reboots a process to run a different program from scratch. Here is the full prototype:
pathis relative or absolute pathname of the executable to be invoked.
argvis the argument vector that should be funneled through to the new executable's
argvgenerally end up being the same exact string.
execvpfails to cannibalize the process and install a new executable image within it, it returns -1 to express failure.
execvpsucceeds, it 😱 never returns 😱.
execvphas many variants (
execlp, and so forth. Type
execvpto see all of them). We typically rely on
execvpin this course.
execvp? An implementation
mysystemto imitate a similar
mysystemfunction, which executes the supplied
commandas if we typed it out in the terminal ourselves, ultimately returning once the surrogate
mysystemspawns a child process to execute that task and waits for it to complete.
execvp, because we know that if it returns at all, it returns a -1. If that happens, we need to handle the error and make sure the child process terminates via an exposed
execvpinside the parent and forgo the child process altogether? Because
execvpwould consume the calling process, and that's not what we want.
fgetsis an overflow-safe variant on
scanfthat knows to read everything up through and including the newline character.