In this article we will discuss how to create a new process using fork() system call.

fork() System Call

A Process can create a new child process using fork() system call.

This new child process created through fork() call will have same memory image as of parent process i.e. it will be duplicate of calling process but will have different process ID.

For example,

Suppose there is a Process “Sample” with Process ID 1256 and parent ID 12. Now as soon as this process calls the fork() function, a new process will be created with same memory image but with different process ID.

Also, process which has called this fork() function will become the parent process of this new process i.e.

Process 1: Sample (pid=1341 | Parent Process ID = 12)

After calling fork() system call,

Process 1: Sample (pid=1341 | Parent Process ID = 12)
Process 2: Sample (pid= 4567 | Parent Process ID = 1341)

As memory image of new child process will be the copy of parent process’s memory image. So, all variables defined before fork() call will be available in child process with same values.

fork() System Call

 

If fork() call is successful then code after this call will be executed in both the process. Therefore, fork() function’s return value will be different in both the process’s i.e.

If fork() call is successful then it will,

  • Return 0 in child process.
  • Return process id of new child process in parent process.

If fork() call is unsuccessful then it will return -1.

 

Let’s see an another example of fork() System call,

Output:

Current process Id : 2769
Parent Process Id : 2769 Its Child Process ID : 2770
Child Process Id : 2770 Its parent ID : 2769

fork() Creates a Clone

New process created by fork() system call will be the copy of calling process but they don’t share any memory. All variables defined in parent process before calling fork() function will be available in child process with same values. But if you modify that variable in any process then it will be not be reflected in other process because they don’t share the address space, memory image is its just copied.

Let’s see an example,

OUTPUT

Child Process :: x = 6
Child Process :: x = 10
Child Process exists
Parent Process :: x = 6

As we can see value of x was 6 before calling fork() function. Therefore in child process value of x remain 6 but then child process modified the value of x to 10. But this change will not be reflected in parent process because parent process has seperate copy of the variable and its value remain same i.e. 6. We added sleep in parent process because to add a delay of 2 seconds and check the value of x in parent process after child process exists.

After fork() call finishes both child and parent process will run parallelly and execute the code below fork() call simultaneously.

Click Here to Subscribe for more Articles / Tutorials like this.