fork() function explanation and examples in Linux C programming Language
fork() is used to create new process by duplicating the current calling process, and newly created process is known as child process and the current calling process is known as parent process. So we can say that fork() is used to create a child process of calling process.
The function - fork()
By using fork() function, we can create a exact same copy of the calling process, this function returns the process id of own and this process id is known as child process id and if we get the parent id of this process it would be the same as the parent process id in which fork() is exist.
fork() Example - C program demonstrating use of fork() in Linux
Syntax:
variable_name = fork();
Consider the example
Output:
Explanation:
This is parent section [Process id: 1252].
1252 is the parent process id which is the process id of the main function too; this is the parent section of new created fork.
fork created [Process id: 1253].
This message will print under the fork section and assigns a new id to the newly created child process.
fork parent process id: 1252.
This message will also print under the fork section, it shows parent process id of the newly created child process which is equivalent to parent process’s id (main process id). Hence we can say newly created child process is the child process of main which is known as parent process.
Another Example using fork()
In this example, we will print natural numbers from 1 to 10 using for loop and we will create a fork() - you will see numbers will be printed twice, because of for(), it will create duplicate copy of the process.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer