Function prototypes
pid_t fork(void);
The magic of Fork is that it is called once, but returns two times, and it may have three different return values:
1. In the parent process, fork returns the PID of the newly created child process
2, in the sub-process, fork returns 0;
3. If an error occurs, fork returns a negative value.
Use:
1, a process wants to replicate itself, so that the parent-child process can execute different pieces of code at the same time.
2. The process wants to execute another program
#include <sys/types.h>#include <unistd.h>intMain () {pid_t pid;/ * There is only one process at this time * /PID = fork ();/ * There are two processes running at the same time * / if(PID <0)printf("Error in fork!\n");Else if(PID = =0)printf("I am the child process, ID is%d\n", Getpid ());Else printf("I am the parent process, ID is%d\n", Getpid ());return 0;}
Before PID = fork (), only one process is executing, but after this statement, it becomes two processes executing, the two processes share the code snippet, and the next statement to be executed is the statement after PID = fork (). Two processes, the original process is called the "parent process", the new process is taken as a "child process", the difference between a parent-child process is the process identifier (PID) is different.
The child process's data space, stack space, is given a copy from the parent process, not a share.
pid_t vfork(void);
1. In the parent process, fork returns the PID of the newly created child process
2, in the sub-process, fork returns 0;
3. If an error occurs, fork returns a negative value.
Use:
Process created with Vfork The main purpose is to execute another program with the EXEC function family, which is the same as the second use of fork
The difference between fork and vfork
Fork: The child process copies the data segment of the parent process, the stack.
Vfork: The child process shares the data segment with the parent process, the stack.
Fork: The order of execution of the parent and child processes is indeterminate
Vfork: Child processes run first, run after parent process
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Linux C creation Process