Fork function return value problem

Source: Internet
Author: User

Fork is one of the most difficult concepts to understand: it executes once but returns two values.

First, let's look at the prototype of the fork function:

# include <sys/types.h>

# include <unistd.h>

pid_t fork (void);

return value:

Negative number: If there is an error, fork () returns-1, no new process is created at this time. The initial process is still running.

0: In child process, fork () returns 0

Positive number: In the negative process, fork () returns the PID of the positive child process

Next we look at how to use fork to create a child process.

The boilerplate code for creating child processes is as follows:

pid_t child;

if ((Child = Fork ()) <0)

/* ERROR Handling */

else if (child = = 0)

/* This is a new process */

Else

/* This is the original parent process */

The Fock function call returns two times, returns the ID of the child process to the parent process, and returns 0 to the child process.

This is because the parent process may have many child processes, so the child process must be traced through the returned child process ID.

While the child process has only one parent process, his ID can be obtained through getppid.

An incisive analysis of fork
The procedure is as follows:
#include <unistd.h>;
#include <sys/types.h>;
Main ()

{

pid_t pid;
Pid=fork ();
if (PID < 0) printf ("Error in fork!");
else if (PID = = 0)
printf ("I am the child process, my process ID is%dn", getpid ());
Else
printf ("I am the parent process, my process ID is%dn", getpid ());
}

The result is

[Email protected] c]#./a.out

I am the child process and my process ID is 4286

I am the parent process, my process ID is 4285

To understand the execution of the fork, you must first clarify the process concept in the operating system. A process that consists mainly of three elements:

O. A procedure that can be implemented;

O. All data associated with the process (including variables, memory space, buffers, etc.);

O. The execution context of the program (execution context).

It is simple to understand that a process represents a state in the execution of an executable program. Operating system management of processes, typically, is done through the process table. Each table entry in the process table that records the situation of a process in the current operating system. In the case of a single CPU, only one process consumes the CPU at each particular time, but there may be multiple active (pending or continued) processes in the system. A register called "program counter, PC," which indicates the position of the next instruction to be executed by the current CPU-consuming process. When the CPU time allocated to a process is exhausted, the operating system saves the value of the register associated with the process to the corresponding table entry in the process table; The context of the process that will take over the CPU of the process, read from the process table, and update the corresponding register (this process is called "Context Exchange" ( Process context Switch) ", the actual contextual exchange needs to involve more data, which is not related to fork, no longer say, the main thing to remember is that the program register PC indicates where the program is currently executing, is the important content of the process context, swapped out CPU process to save the value of this register, the process of swapping into the CPU, but also according to the process table to save the process of executing context information, update this register.

Well, there are these concepts at the bottom, you can say fork. When your program executes to the following statement:

Pid=fork ();

The operating system creates a new process (child process), and establishes a new table entry for it in the process table accordingly. The new process and the executable procedure of the original process are the same program; The majority of the context and data is the copy of the original process (parent process), but they are two separate processes! At this time the program register PC, in the context of the parent, child process, claims that the process is currently executing to the fork call is about to return (at this time the child process does not occupy the CPU, the child process of the PC is not really saved in the register, but as the process context is saved in the process table in the corresponding table key). The question is how to go back and split up in the parent-child process.

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

The child process is dispatched at some later time, its context is swapped in, the CPU is occupied, and the operating system implements the fork, which causes the fork call in the child process to return 0. So in this process (note that this is not the parent process Oh, although it is the same program, but this is another execution of the same program, in the operating system this execution is represented by another process, from the perspective of execution and the parent process is independent of each other) pid=0. While this process continues to execute, Pid<0 is not satisfied in the IF statement, but Pid= =0 is true. So output I am the child process ...

Why does it seem that the two branches of the program that are mutually exclusive are executed? This is certainly not possible in a single execution of a program, but the two lines of output you see are from two processes, both of which are executed two times from the same program.

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. Instruction pointers are exactly the same, but only a little different, if Fork succeeds, the return value of fork in the child process is 0, the return value of 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.

It can be imagined,2 processes are running at the same time, and Unison, after fork, they do different jobs, that is, bifurcation。 This is the reason why fork is called fork.

After using fork () in the program section, the program forks and derives two processes. The specific which runs first looks at the system's scheduling algorithm.

If a parent-child process is needed, it can be resolved by means of the primitive language.

Two:
Creation of the process:
Creating a system call to a process is straightforward. We just call the fork function.
# include <unistd.h>
pid_t Fork ();

When a process calls fork, the system creates a child process.This child process differs from the parent process in that it has only his process ID and parent process ID, and the others are the same. Just like the parent process cloning (clone) itself. Of course it doesn't make sense to create two identical processes. To differentiate between parent and child processes, we must track the return value of the fork. Fork returns a value of 1 when the fork is lost (insufficient memory or the user's maximum number of processes has been reached), otherwise it is important to return values of the forked. Returns the ID of the child process for the parent process fork, and 0 for the fork child process. We are using this return value to differentiate the parent-child process. Why does the parent process create a child process? As we said earlier, Linux is a multi-user operating system, and at the same time many users are competing for the resources of the system. Sometimes processes create child processes to compete for resources in order to complete tasks earlier. Once a child process is created, the parent-child process continues to execute from the fork, competing for the resources of the system. Sometimes we want the child process to continue, and the parent process blocks until the child process finishes the task. At this point we can call wait or waitpid system call.

To summarize, there are three:

1, the process of deriving a child process, that is, the parent process, its PID is unchanged;

2, the sub-process, fork returned to it 0, but its PID is definitely not 0, the reason that fork returns 0 to it, because it can call Getpid () at any time to obtain their own PID;

3,fork the parent-child process is not sure who runs first or who ends first unless synchronization is used. It is not right to think that the child process is over stepfather process is returned from fork, which is not the case with fork, vfork.

Fork function return value problem

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.