The fork () function allows the process to copy a sub-process that is almost identical to its own, and the fork function call returns two times:
Once in the parent process, once in the child process. Its return value depends on the current process, and if the child process returns 0, the parent process returns the child process PID.
In general, parent-child processes have the following characteristics:
1 The parent and child processes are concurrently executed;
2 the same but relatively independent address space;
3 Share file IO.
A simple code looks like this:
1#include <unistd.h>2#include <stdio.h>3 4 intMain ()5 {6 //int i=0;7 pid_t fpid;8Fpid=fork ();9 if(fpid<0)Ten { Oneprintf"Error in fork () \ n"); A } - Else if(fpid==0) - { theprintf"pid==%d\n", Getpid ()); -printf"fpid=0\n"); - } - Else if(fpid>0) + { - +printf"pid==%d\n", Getpid ()); Aprintf"fpid!=0\n"); at } - - return 0; -}
Post-compilation results:
1 $:~/sb/codetest$./a.out2 fpid=72623 pid==72614 fpid!=0
5 fpid=06 pid==72627 fpid=0
Apue's first fork ()