Both the fork function and vfork () function can be used to create a process fork (). an existing process can call the fork function to create a new process. A new process created by fork is called a child process ). The fork function is called once but returns two results. The only difference between the two responses is that both the subprocess fork function and vfork () can be used to create a process.
Fork () an existing process can call the fork function to create a new process. A new process created by fork is called a child process ). The fork function is called once but returns two results. The only difference between the two responses is that the child process returns 0 and the parent process returns the child process ID. A child process is a copy of the parent process. it obtains a copy of the data space, heap, stack, and other resources of the parent process. Note that sub-processes hold "copies" of the above bucket, which means that the parent and child processes do not share these buckets. Vfork () generates a new sub-process. however, the child process created by vfork shares the data segment with the parent process (refer to Baidu Library, but it also shares the heap, and the running results show that ), in addition, the child process created by vfork runs before the parent process. Example 1:
# Include
# Include
# Include
Int main (void) {pid_t pid; int _ num = 8; if (pid = vfork () <0) {// perror ("vfork is failed"); exit (1);} else if (pid = 0) {// run the sub-process printf ("this is child process \ n"); _ num ++; printf ("the num is: % d \ n ", _ num); exit (0);} else {//> 0 vfork () the returned value is the subprocess pid printf ("this is parent process \ n "); _ num ++; printf ("the num is: % d \ n", _ num);} return 0 ;}
Running result:
Example 2:#include
#include
#include
int main(void){ pid_t pid; int _num=8; if ((pid = fork()) < 0) { perror("fork is failed"); exit(1); } else if (pid == 0) { printf("this is child process\n"); _num++; printf("the num is :%d\n",_num); exit(0); } else { printf("this is parent process\n"); _num++; printf("the num is :%d\n",_num); } return 0;}
Running result: