The bifurcation function in computer programming. Return value: If the call is successful, two values are returned, the child process returns 0, and the parent process returns the child process token; otherwise, an error returns-1. The fork function divides the running program into 2 (almost) identical processes, each of which initiates a thread that executes from the same location in the code. The threads in both processes continue to execute, as if two users had started two copies of the application at the same time. Here is an example of how the fork function works.
#include <unistd.h> #include <stdio.h> int main () { pid_t fpid;//fork returns fpid int cnt=0; Fpid=fork (); if (Fpid < 0) printf ("Error in fork!"); else if (Fpid = = 0) { printf ("I am the child process, process ID:%d\n", Getpid ()); cnt++; } else { printf ("I am the parent process, process ID:%d\n", Getpid ()); cnt++; } printf ("Count:%d\n", CNT); return 0; }
Run GCC Fork.c-o fork to get the fork executable file, run:./fork
The following results are obtained:
I am The parent process, process id:1924count:1i am the child process, process id:1925count:1
After the fpid=fork () statement, two processes execute code starting with if (fpid<0). Because the stack segment of the parent process is copied at copy time, two processes are stuck in the fork function, waiting to be returned. So the fork function returns two times, once in the parent process, and the other in the child process, and the return value of the two times is different.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Linux fork function