Fork creates a new process. The newly created process is a sub-process. It is a copy of the code of the parent process and is usually used on the server where multiple processes are processed, you can also run independent code in a sub-process.
You can use getpid to determine whether the current process is a child process or a parent process.
Let's look at the example below:
# Include <sys/types. h>
# Include <unistd. h>
# Include <stdio. h>
Int main ()
{
Pid_t PID;
Static int n = 0;
Printf ("fork! /N ");
Switch (pid = fork ())
{
Case-1:
{
/*. PID.-1. Fork ....*/
/*........*/
/*..........*/
Perror ("the fork failed! ");
Break;
}
Case 0:
{
/* Pid.0 ....*/
Printf ("[Child] I am child! /N ");
Printf ("[child] getpid = [% d]/n", getpid ());
Printf ("[child] pid = [% d]/n", pid );
Break;
}
Default:
{
/* PID... 0 ....*/
Printf ("[Parent] I am parent! /N ");
Printf ("[Parent] getpid = [% d]/n", getpid ());
Printf ("[Parent] pid = [% d]/n", pid );
Break;
}
}
Printf ("n = [% d]/n", N ++ );
Return 0;
}
This example is compiled using GCC in Linux. The running result is as follows:
Fork!
[Child] I am child!
[Child] getpid = [7422]
[Child] pid = [0]
N = [0]
[Parent] I am parent!
[Parent] getpid = [7421]
[Parent] pid = [7422]
N = [0]