Use of fork in linux-general Linux technology-Linux programming and kernel information. The following is a detailed description. 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:
CODE: # include
# Include
# Include
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;
} |