# Include <unisth. h>
Pid_t fork (void)
The fork function is called once and returns two times. The return value of a child process is 0, and that of a parent process is the ID of the child process.
The child process and the parent process continue to execute the commands after the fork call. The child process is a copy of the parent process, and the child process obtains the data space of the parent process, heap and stack copies. Note: This is a copy of the sub-process. The Parent and Child processes do not share these buckets. Parent-Child process share body section
# Include <stdio. h> # include <sys/types. h> # include <unistd. h> int glob = 6; // global variable. In the heap, char Buf [] = "A write to stdout \ n"; int main () {int var; // local variable, pid_t PID in the stack; Var = 88; If (write (stdout_fileno, Buf, sizeof (BUF)-1 )! = Sizeof (BUF)-1) {perror ("write error");} printf ("before fork: \ n"); If (pid = fork ()) <0) {perror ("fork error");} else if (pid = 0) {glob ++; var ++;} else {sleep (2 );} printf ("pid = % d, glob = % d, Var = % d \ n", getpid (), glob, VAR); exit (0 );}
Output:
A write to stdout
Before fork:
PID = 4989, glob = 7, Var = 89
PID = 4988, glob = 6, Var = 88
Fork is used in two ways:
1. A parent process wants to copy itself so that the parent and child processes can execute different code segments at the same time.
2. A process needs to execute a different program. In this case, the child process immediately calls exec after returning from fork.