How does fork return twice?

Source: Internet
Author: User
I have been wondering how to return the fork method twice. I read the book carefully today. In fact, it is unclear to say "return twice. Fork does not actually return twice, but it still returns once, but the OS's fork operation makes it seem that it has returned twice. I found an article which is still clear. Add it to favorites.
Http://hi.baidu.com/gsk_neu/blog/item/31cdebefcf24ee36acafd5ea.html

To understand the execution process of fork, we must first clarify the concept of "process" in the operating system. A process mainly contains three elements:

O. an executable program;
O. All data associated with the process (including variables, memory space, buffers, etc );
O. Execution context of the program ).

Simply put, a process represents a State in one execution process of an executable program. The management of processes by the operating system is typically completed through the process table. Each table entry in the table records a process in the current operating system. For a single CPU, only one process occupies the CPU at each specific time, but there may be multiple active (waiting for execution or continuing execution) processes in the system at the same time.

A register called "program counter (PC)" indicates the position of the next instruction to be executed by the CPU-consuming process.

When the CPU time allocated to a process is used up, the operating system saves the value of the process-related registers to the corresponding table items of the process in the progress table; read the context of the process that takes over the CPU of the process from the Progress table and update the corresponding register (this process is called "process context switch )", the actual context exchange requires more data, which is irrelevant to fork. Remember that the program register PC indicates where the program has been executed and is an important part of the process context, the process for switching out the CPU needs to save the value of this Register, and the process for switching into the CPU should also update this register according to the execution context information of this process saved in the progress table ).

Well, with these concepts, we can say fork. When your program runs the following statement:
PID = fork ();
The operating system creates a new process (child process) and creates a new table item for it in the process. The new process and the executable program of the original process are the same program. The context and data are mostly copies of the original process (parent process), but they are two independent processes! At this time, the program register PC claims in the context of the Parent and Child processes that the current fork call is about to return (at this time, the child process does not occupy the CPU, the PC of the sub-process is not actually saved in the register, but stored as the process context in the corresponding table in the progress table ). The problem is how to return data. In the Parent and Child processes, we will part with each other.

The parent process continues to execute. The operating system implements fork so that the call returns the PID (a positive integer) of the created child process in the parent process ), therefore, in the following if statement, neither of the two branches of PID <0, pid = 0 will be executed. So output I am the parent process...

The Subprocess is scheduled at a later time, and its context is swapped in to occupy the CPU. The fork Implementation of the operating system makes the fork call in the subprocess return 0. So in this process (note that this is not a parent process. Although it is the same program, this is another execution of the same program, in the operating system, this execution is represented by another process. From the execution point of view, it is said that the parent process is independent of each other.) pid = 0. When this process continues to run, if statement PID <0 does not meet, but pid = 0 is true. So output I am the child process...

I'm wondering why the two branches in the program are executed. This is of course impossible during one execution of a program; but the two lines of output you see come from two processes, which come from two executions of the same program.

In addition:The East and West sub-processes of the parent process before fork can be inherited, but after fork, the sub-process has no inheritance relationship with the parent process. What is created in a child process is a child process, and what is created in a parent process is a parent process. It can be totally regarded as two processes.

Let's look at an example:

# Include <unistd. h>;
# Include <sys/types. h>;

Main ()
{
Pid_t PID;
Printf ("fork! "); // Printf (" fork! /N ");
PID = fork ();

If (PID <0)
Printf ("error in fork! ");
Else if (pid = 0)
Printf ("I am the child process, my process ID is % d/N", getpid ());
Else
Printf ("I am the parent process, my process ID is % d/N", getpid ());
}

 

The result is
[Root @ localhost C] #./A. Out
Fork! I am the child process, my process ID is 4286
Fork! I am the parent process, my process ID is 4285

But changed to printf ("fork! /N "); the result is
[Root @ localhost C] #./A. Out
Fork!
I am the child process, my process ID is 4286
I am the parent process, my process ID is 4285

Why is there only one fork! Printed? Why are there two in the previous one?

Apue's p143 said:
Fork previously called printf once. After fork, the row of data is still in the cache, and then the data space of the parent process is copied to the child process. The cached data is also copied to the child process.

Add a function fflush (0) between printf () and fork () to see how it is added.

# Include <stdio. h>
Int main (void)
{
Printf ("hello ");
Fflush (stdout );
Fork ();
Exit (0 );
}
In this way, only the hello
The reason is:: Stdin, stdout, and stderr are both row buffers.

There will be no output for clearing the buffer: setbuf (stdout, null) or setvbuf (stdout, null, _ ionbf, 0)

 

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.