Explain about fork() process in Linux? Provide an example.
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.