Summary of the fork () system call in Linux

Source: Internet
Author: User
Tags session id signal handler

A new process created by Fork is called a subprocess (child process). The function is called once, but returns two times. The difference of two returnsis that the return value of the child process is 0, and the return value of the parent process is the process ID of the new process (child process). The reason for returning the child process ID to the parent process is that because there can be more than one child process for a process, there is no function that enables a process to obtain the process ID of all its child processes. For a child process, fork returns 0 to it because it can call getpid () to get its own PID at any time, or call Getppid () to get the ID of the parent process. (Process ID 0 is always used by the interchange process, so the process ID of a child process cannot be 0).

After fork, the operating system replicates a child process that is exactly the same as the parent process, although it is a parent-child relationship, but in the operating system it appears that they are more like siblings, that the 2 processes share the code space, but that the data space is independent and that the content in the child process data space is a complete copy of the parent process. The instruction pointer is also exactly the same, the child process has the parent process currently running to the location (the two process of the program counter PC value is the same, that is, the child process starts from the fork to execute), but a little different, if the fork is successful, the return value of fork in the sub-process is 0, The return value of the fork in the parent process is the process number of the child process, and if the fork is unsuccessful, the parent process returns an error.
As you can imagine, 2 processes are running at the same time, and Unison, after the fork, they do different jobs, that is, bifurcation. That's why fork is called fork.

As for the first run, it may be related to the operating system (scheduling algorithm), and this problem is not important in the practical application, if the parent-child process should be coordinated, can be solved by the primitive language method.

an existing process can callfork fork The new process created is called a child process ( child Process fork function was called once but returned two times. The only difference of two returns is that the child process returns 0 id .

< Span style= "margin:0px; padding:0px "> Child process is a copy of the parent process, It gets the parent process data space, heap, Copies of resources such as stacks file locks and pending signals is not INHERITED.&NBSP, " 3 "

if The call to fork () is executed successfully, Unix would span>

< Span style= "margin:0px; padding:0px ">①&NBSP; make-identical copies of address spaces, one for the parent and the other for th E child.

< Span style= "margin:0px; padding:0px ">②&NBSP; both processes would start their execution at the next statement following the fork () Call.

3, why < Span style= "Font-family:times New Roman; margin:0px; padding:0px ">fork will return two times?

because at copy time < Span style= "margin:0px; padding:0px "> Copy the stack segment of the parent process So two processes are stuck in fork function, wait for return. Because fork

after A new child process is created, both processes would execute the N Ext instruction following the fork () system call.

call fork After the code has two copies, all from fork returned in the function.

Please Note that Unix Would make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes has separate address spaces

Note that the child process inherits the I/O buffering of the parent process, which is buffered in printf, which inherits the I/O buffering of the parent process without \ r \ n Brush buffering

(1), The forked child process inherits the following properties from the parent process:

    • Uid,gid,euid,egid
    • Additional group ID(sgid,supplementary Group ID)//Sgid introduced because sometimes you want this user to belong to several other departments, the GID of these other departments is Sgid
    • Process group ID, session ID
    • SUID tags and sgid tags
    • Control Terminal
    • Current working directory/root directory
    • Umask when the file is created
    • File descriptor for File identifier (CLOSE-ON-EXEC)
    • Signal shielding and processing
    • Storage mappings
    • Resource limits

(2), the following are different parts:

    • Different PID
    • Process time is emptied
    • File lock does not inherit
    • The unhandled signal is emptied.

Child processes inherit from the parent process to:
1. Eligibility for the process (real/active (Effective)/saved (saved) user number (UIDs) and group number (Gids))
2. Environment (Environment)
3. Stacks
4. Memory
5. Open the file descriptor (note that the location of the corresponding file is shared by the parent-child process, which can cause ambiguity)
6. Close on Execution (CLOSE-ON-EXEC) flag (Translator Note: The CLOSE-ON-EXEC flag can be set by Fnctl () to the file descriptor, POSIX.1 requires that all directory streams must be closed when the EXEC function is called. In more detail, see Advanced Programming for UNIX Environment W. R. Stevens, 1993, Yu Jinyuan, etc. (hereinafter referred to as "advanced Programming"), 3.13 knots and 8.9 sections)
7. Signal (signal) control settings
8.nice Value (Translator Note: Nice value is set by the Nice function, which represents the priority of the process, the smaller the value, the higher the priority)
Process scheduling category (Scheduler Class) (Translator Note: The process scheduling category refers to the class that the process belongs to when it is dispatched in the system, different classes have different priorities, and the process Scheduler calculates the global priority of each process based on the process scheduling category and the nice value. Prority), priority-high process priority execution)
8. Process group number
9. Session ID (Translator NOTE: Translated from advanced programming, refers to the session ID of the session to which the process belongs, a conversation period consists of one or more process groups, see Advanced Programming Section 9.5 for more detailed instructions)
10. Current working Directory
11. Root directory (Translator note: The root directory is not necessarily "/", it can be changed by the chroot function)
12. File mode to create a shielded word (File mode creation mask (umask)) (Translator Note: The translation is from Advanced programming, which refers to: Create a new file default screen word)
13. Resource Limitations
14. Control Terminal

the child process is unique:

Process number
1. Different parent process number (Translator Note: The parent process number of the child process is different from the parent process number, the parent process number can be obtained by the GETPPID function)
2. Copy of your own file descriptor and directory stream (translator Note: The directory stream is created by the Opendir function, because it is read sequentially, and is called "Directory Flow")
3. The child process does not inherit the process of the parent process, body (text), data and other locked memory (locks) (Translator Note: Locked memory refers to locked virtual memory pages, locked, 4. The kernel is not allowed to swap out when necessary (page out), see the GNU C Library Reference Manual Edition 2.2, 1999, 3.4.2)
5. System time in the TMS structure (translator Note: The TMS structure can be obtained by the Times function, which holds four data to record the time that the process uses the central processing Unit (cpu:central processing units), including: User Time, System time, total user time for each child process , total time for each sub-process of the system)
6. Resource Usage (resource utilizations) set to 0
8. Block signal sets are initialized to an empty set (translator Note: The original text is ambiguous here, the translation is slightly modified according to the Fork Function manual page)
9. Do not inherit timers created by the Timer_create function
10. Do not inherit asynchronous inputs and outputs

(3), fork system call to pay attention to the place

After the fork system is called, the parent-child process is executed alternately.
If the parent process exits first and the child process does not exit then the parent process of the child process becomes the init process. (Note: Any process must have a parent process)
If the child process exits first and the parent process does not exit, the child process must wait until the parent process captures the exit state of the child process to really end, otherwise the subprocess becomes a zombie process.

A child process exit sends a SIGCHLD signal to the parent process, optionally ignoring or using a signal handler to receive processing to avoid the zombie process.


(4) Copying copy on write

Replication is unnecessary if multiple processes are to read copies of their own portion of the resource.
Each process simply saves a pointer to the resource.
If a process modifies a "copy" of its own resource, that resource is copied. That's what it means when it's written.

For example, fork is based on write-time replication, and read-only code snippets can be shared.

If you use Vfork, the child process and the parent process occupy the same memory image, and the child process modification affects the parent process. The parent process is also run only after the child process executes exec/exit. in fact, the stack space occupied by the child process is the stack space of the parent process, so you need to be very careful. If the vfork child process does not have an EXEC or exit, the child process executes until the program exits and the parent process begins execution. And this time the memory of the parent process has been completely written down.


(5), fork after the parent-child process to share files


The child process inherits the file descriptor opened by the parent process, so the reference count for each open file is 2.



Summary of the fork () system call in Linux

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.