(1) Definition of fork ()
The fork () function is the only way to derive a new process from UNIX, declared as follows:
[CPP]View Plaincopy
- #include <unistd.h>
- pid_t fork (void);
What we need to understand is that by invoking the fork () method, the method returns two times. Once is returned once in the calling process (that is, the parent process of the derived child process), and the return value is the process ID of the newly-derived process. Once is returned in the child process, the return value is 0, which represents the current process as a child process. If the return value is-1, it represents an error in the process of deriving a new process.
So in the program, we can determine whether the current process is a parent or a child process based on this return value to implement some specific actions. For example:
[CPP]View Plaincopy
- int main ()
- {
- pid_t pid;
- if (PID = fork ()) = 0)
- {
- //TODO: Implement specific actions in child processes
- // ...
- Exit (0); //End Child process
- }
- //TODO: Implement specific actions on the calling process (parent process)
- }
(2) The substantive process of fork ()
In the parent process, the call to fork () derives a new process, which is actually the equivalent of creating a copy of the process, that is, the resources owned by the process before the fork () are copied into the new process. The network server can also take this method of deriving a new process when it processes concurrent requests: The parent process calls accept () and calls fork () to process each connection. Then, the accepted connected socket interfaces are then shared in the parent-child process. Generally speaking, the child process will read and write in this connection socket interface, the parent process closes the connected socket (refer to: http://blog.csdn.net/moxiaomomo/article/details/6791763)
(3) Use of fork ()
Fork () has two typical uses: (1) a process replicates itself so that each copy can do its own work independently, and the data can be processed in parallel in a multi-core processor. This is also a typical use of a network server, multi-process processing multi-connection requests. (2) One process wants to execute another program. For example, if a software contains two programs, and the main program wants to move another program, it can call fork to create a copy of itself, and then replace it with a new program that will run with the EXEC function.
"Operating System" Linux Create Child Process--fork () method