Share & learn

Through Innovative Digital Library

Explain about fork() process in Linux? Provide an example.

Explain about fork(). Provide an example with explanation.


Posted by Nikheel Bhasmare on November 6th 2017 06:37 AM

fork() is a system call. fork() is used to create child process of calling process. With the help of fork() function we can create same copy of the calling process, it also returns process id of its own. This process id is known as child process id. The child process has a unique process ID. The child process has a different parent process ID (that is, the process ID of the parent process). The child has a parent process ID which is same as the PID of the process that created it. After a new child process created, both processes will execute the next instruction after the fork() system call. The call to fork() will return 0 to the child process, and the pid of the child process to the parent process. A child process uses same pc (program counter), same CPU registers, same open files which use in parent process. It takes no parameters and return integer value. Below are different values returned by fork(). 1. Negative Value: Child process creation unsuccessful. 2. Zero: New child process created. 3. Positive value: Returned to parent or caller. The value contains process ID of newly created child process. Refer sample code : Take a look at this example. Here we are printing numbers from 1 to 5 using for loop. If we use fork() in here same loop will be repeated for child. That means loop will occur two times, as fork() creates child process. The child has a parent process ID which is same as the PID of the process that created it. Here we can see that Parent process ID of child process and process ID of the process that created it both are same.

#include <stdio.h>
#include <unistd.h>
int main()
int iid;
id fork();
id 0){
/*parent process*/
printf("Parent Process Execution and id is : %d \n",getpid());
    else if(
id == 0){
/*child process*/
printf("\nfork created... Child Process id : %d, Parent Process id :  %d \n",getpid(),getppid());
/*fork creation failed*/
printf("\nfork creation failed\n");
printf("Printing the numbers from 1 to 5\n");
< = 5i++)
printf("%d "i);
/*Running this program will print something similar to what is shown below in the image, though results may vary from one run to the next.*/
Answer Question

Your email address will not be published. Required fields are marked *

  • Minimum 20 character

related questions

Most liked questions

Most answered questions

M4GS Refresh
M4GS Refresh
Forgot password
Ask a Question
Minimum 20 character
Minimum 20 character
Minimum 20 character
M4GS Refresh