fork() function is used to create a child process. The process who calls this function is called parent process. Once the fork() function is called, it creates an exact copy of the calling process.
The syntax of the function is:
pid_t fork(void);
where pid_t is an unique integer which refers the process id.
As we mentioned, fork() function will creates an exact copy of the calling process; the data available before calling fork() function is also available in child process. But the data is in two different address spaces. That means, if you change the data in parent process; it will not affect in child process’s data.
Lets see the below code example:
#include <unistd.h> #include <stdio.h> void main() { int var = 1000; printf("Hello, World!\n"); pid_t pid = fork(); if ( pid > 0 ) { printf("This is Parent Process.\n"); var++; printf("The data is %d.\n", var); wait(); printf("Child Process ended.\n"); } else { printf("This is Child Process.\n"); printf("The data is %d.\n", var); } }
From above code, once we call fork() function, it will create a child process and returns its process id to parent process (calling process). And it returns the process id “0” to itself.
You got confused?
As mentioned earlier fork() function will creates a child process. After this function call our code will runs in two different processes; in parent process and in child process. What about return value? Yes, within the fork() function, the child process gets created. So, now the fork() function should return two values; one is in parent process another once is child process.
To differentiate which process is parent and child; fork() returns process id of child process in parent process and “0” to child process. That is the reason, we put parent process code inside ( pid > 0 ) condition. So, we have written separate code for parent process and child process.
Observe that we are modifying the variable’s value in parent process; but it is not affecting the value in child process. It proved that two copies of data maintaining in their (processes) own address spaces.
Once child process is created, the program control switches between parent process and child process. Once the child process finished it terminates from memory. The same way, once parent process finished, it removes from memory. What happened if parent process finish before its child process? The child process will become an orphan. To resolve this, we used wait() command in parent process code. wait() keeps process in wait state until its children are finished. Because of this, from our code, child process always finished first.
// Malin