Linux Process Programming – fork()

What is a process?

In computing, a process is an instance of a computer program that is being executed. It contains the program code and its current activity. Depending on the operating system (OS), a process may be made up of multiple threads of execution that execute instructions concurrently.

What does fork() do?

The fork() is a system which will create a new child process. The child process created is an identical process to the parent except that has a new system process ID. The process is copied in memory from its parent process, then a new process structure is assigned by the kernel. The return value of the function is which discriminates the two threads of execution. A 0 is returned by the fork function in the child's process, while the PID of the child process is returned in the parent's process.

In brief, fork() creates a child process that differs from the parent process only in its PID and PPID (the Parent PID, the creator of the process), and in the fact that resource utilizations are set to 0. File locks and pending signals are not inherited. Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.

Here is an example c program using fork() system call. Notice the comment.

/* Example of use of fork system call */
#include <stdio.h>
#include <iostream>
#include <string>
// Required by for routine
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
  int pid;
  pid = fork();
  if (pid < 0) { // error occurred 
	  fprintf(stderr, "Fork failed!\n");
  }else if (pid == 0) { // child process 
	  printf("I am the child, return from fork=%d\n", pid);
	  execlp("/bin/ps", "ps", NULL);
  }else { // parent process 
	  printf("I am the parent, return from fork, child pid=%d\n", pid);
	  printf("Parent exiting!\n");


programcreek:~/cdtworkspace/CPractice/src> ./a
I am the parent, return from fork, child pid=15053
Parent exiting!
I am the child, return from fork=0
programcreek:~/cdtworkspace/CPractice/src>   PID TTY          TIME CMD
15033 pts/0    00:00:00 tcsh
15053 pts/0    00:00:00 ps

At first, parent process runs, print real child pid, and exit.
Then, child process runs, print pid 0.

Think about why parent process runs before child process?

Category >> C/C++  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Sudhi

    highly helpful, hoping for more theortical portion