Using the exec family of system calls

The job of exec is to replace the current process with a new process. Note the use of the word replace. Once you call exec, the current process is gone and the new process starts. If you want to create a separate process, you must first fork, and then exec the new binary within the child process. Listing 4 shows such a scenario.

The code in Listing 4 first defines an array, with the first element being the path to the binary that is to be executed, and the remaining elements acting as the command-line parameters. The array is null-terminated per the man pages. After returning from the fork system call, the child process is instructed to execv the new binary.

The call to execv first takes a pointer to the name of the binary to be run, and then a pointer to the array of parameters that you declared earlier. The first element of the array is actually the name of the binary, so it’s really the second element where the parameters start. Note that the child process never returns from the call to execv. This shows that the running process is replaced by the new process.

There are other system calls to exec a process, and they differ by how they accept parameters and if environment variables need to be passed. execv(2) is one of the simpler ways to replace the current image, because it doesn’t need information about the environment and it uses the null-terminated array. Other options are execl(2), which takes the parameters in individual arguments, or execvp(2), which also takes a null-terminated array of environment variables. To make matters more complicated, not all operating systems support all variants. The decision of which one to use depends on the platform, coding style, and whether you need to define any environment variables.

Related Post