#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
pid_t pid1;
pid_t Pid2;
pid1 = fork ();
Pid2 = fork ();
printf ("pid1:%d, pid2:%d\n", Pid1, Pid2);
}
Output:
pid1:3411, pid2:3412//parent process returns two times
pid1:0, pid2:3413//Sub-process 1 return two times
pid1:3411, pid2:0//Sub-process 2 return once
pid1:0, pid2:0//Sun Process 3 to return once
1) The fork function is always "called once, returns two times", is called once in the parent process, and is returned once in the parent and child processes. The return value of fork in the child process is 0, and the return value in the parent process is the ID of the child process.
2) The child process copies the current state of the parent process when it is created (the same as the PCB information, and the same for the user state Code and data).
3) The result of the program operation is basically the parent-child process alternately printing, but this is not certain, depending on the operation of other processes in the system and the kernel scheduling algorithm.
The fork in Linux is implemented with clone. The process of fork and the parent process is not the same as the PID, others are the same (basically), that is, the parent process copies a copy. Note, however, that the copy action does not occur until the child process is actually executed because Linux considers clone to be exec. EXEC copies the code that the process actually executes to the address space. Because a simple fork is a copy of a parent process, not very useful.
What's the use of fork?