fork() vs exec()
- The fork system call creates a new process.
- The new process created by fork() is copy of the current process except the returned value. The exec system call replaces the current process with a new program.
[Note: unistd.h is the name of the header file that provides access to the POSIX operating system API]
fork and exec system calls
- The use case is to execute a program in Linux environment.
- To execute a program, a process needs to be created. So, some process, already in existence, has to create a process for the program to be executed. In a typical command line scenario, the existing process is the shell.
- The shell creates a new process using the fork system call. The (earlier) existing process is the parent process and the newly created process is the child process.
- The child process is a clone of the parent process. Its code, data and stack segments are a copy of the parent. There is a major difference, though. Since these are two different processes, their process ids are different.
- The return value of fork in parent and child are different. In the parent process, the return value of the fork system call is the process id of the child. In the child process, fork returns zero. Indeed, based on the return value of the fork system call, a process can decide whether it is the parent or the child and act accordingly.
- What is the use of having a process which is a copy of its parent? Not much. But, then, the fork system call is to be used in conjunction with the exec system call.
- To be a little more precise, exec, actually, refers to a family of six system calls with names execl, execv, execlp, execvp, execle and execvpe.
- The differences between the six are rather fine and, in most cases, any one of the six forms can be used. We will use the family name exec to mean one of the exec system calls.
- The point is that, after fork, there are two processes, the parent and the child. In most cases, the child process, executes an exec system call to execute the program of interest.
- When the child process exec’s a program, it initializes its code and the data segments with the program’s code and data.
- The old code and data (of the copy of the parent) are overwritten with the new code and data of the program exec’ed.Thus, we can conclude that fork and exec system calls are mostly used together. Without fork, exec is of very limited use and without exec, fork is hardly of any use.
- As an example, let’s write two programs, parent and child.
- We will execute parent from the shell’s command line.
- The parent would fork a child process and the latter would exec the child program in it.
- The parent would wait for the child to do its work and terminate.