Fork

The system call:

int pid;

pid = fork();

The execution of the fork system call creates a new process that is an exact copy of the calling process (code and data segments). After execution of the call, you have two heavy-weight processes: the parent and the child. They do not share memory. The child has a copy of all of the data structures of the parent at the time of the fork. Therefore, any resources obtained from the operating system prior to the execution of the fork is known by both the child and the parent.The child "knows" everything the parent "knows" at the time of the fork.

Both the parent and the child continue executing at the instruction following the fork. The operating system schedules both processes to run. The value returned by the fork system call, above, pid, has a different value in the parent and the child. The system call returns the process id of the newly created child to the parent. The system call returns 0 to the child. Therefore, your code can easily differentiate between the parent and the child. From now on, changes made to variables are independent of each other.

The getpid() function should be used for each process to learn its pid. The getpid() function returns the pid of the caller.
 

System calls usually return -1 if the call failed and sets the global variable errno to the error returned by the kernel. The values that errno can take along with a brief description of each error can be found in the header file <sys/errno.h>.

After the processes have performed their duties, they terminate. The parent must wait for the child to terminate before it terminates. Otherwise, the child becomes an orphan.

The parent uses the wait system call to wait for the child: wait(&statloc); where statloc is an integer. See man pages for more information.


Last modified 1:28 PM 11/07/2025

This page is copyright protected © by Barbara Bracken