Little talk process: Linux Process Control programming (fork, Vfork)

Source: Internet
Author: User

The so-called process control is that the system uses a number of specific functions of the program to create processes, undo processes, and complete the process of transitions between various states,

so as to achieve multi-process efficient concurrent execution and coordination of resource sharing purposes. Process Control is an important task of process management and processor management.


1. Fork () Create process
In Linux systems, the first process (the root process) is created by the system, except after the system is started.

all remaining processes must be created by a process that already exists The newly created process is called a child process, and the process that creates the child process is called the parent process .

Processes with the same parent process are called sibling processes.

The way to create a new process in Linux is to use the fork () function.
The fork () function is used to create a child process in a "copy" manner based on the existing process.


When you call fork (), fork () passes all the resources of the parent process through the "copy" of the data structure to the child process:
To have the child process use the same Code snippet as the parent process
Copies the data and stack segments of the parent process to a child process so that all the data for the parent process can be left to the child process.

However, the address space of the parent-child process is separated and no more data is shared, so there is no effect on each other.

The execution of a child process is independent of the parent process, and the data sharing of the parent-child process requires a dedicated communication mechanism.
Create a child process control block using the "copy" method
Enclose the word copy in quotation marks because the copy is not completely duplicated. Because the contents of some items in the parent process control block must be modified according to the characteristics of the child process,

such as: identification of the process, status, and so on. In addition, the child process control block must have a domain and private space that represents its parent process, such as data space, user stack, and so on.


The child process that is obtained by using the fork () function is a "replica" of the parent process that inherits the address space of the entire process from the parent process:
Includes process context, code snippet, process stack, memory information, open file descriptor, signal control setting, process priority, process group number,

The current working directory, root directory, resource limits, and control terminal, and the child process is unique only to its process number, resource usage and timer and other small amount of information.





The parent and child two processes run the same program:

Because the child process is almost a full copy of the parent process, the parent-child two processes run the same program.

It is therefore necessary to differentiate them in one way, otherwise the two processes cannot do different things.


Sub-process, fork () returns 0
Parent process, fork () returns the ID of the child process (>0)

When the fork () function is actually executed in the parent process, the parent process replicates a child process, and the parent-child process's code runs concurrently in two address spaces, starting with the return of the fork () function.

Thus two processes get the return value of their owning fork (), where the return value of fork () in the parent process is the process number of the child process, and the fork () in the child process returns 0.

Therefore, the return value can be used to determine whether the process is a parent or child process.
If the fork () creation process fails, 1 is returned.



Fork () Workflow for system calls:



The fork () function is insufficient:
When using the fork () function, it "replicates" most of the code snippets, data segments, and stack segments in the parent process, making the fork () function more costly.
When a child process is created, the child process next calls exec () to execute another program, and the previous copy work will be redundant
If the data segment and stack segment of the program that calls the fork () function are large, the overhead of copy work can seriously affect system performance.
Workaround: Adopt copy-on-write (copy on Write) technology.
Replication is only "logical", not "physical": when actually executing fork (), the data segments and stack segments of two processes on the physical space are still shared,

When a process writes a data, the data between the two processes is different, and the system separates the "pages" from the physical.

This allows the system to have a minimal overhead in space.

Fork () Function Example:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h>int main () { pid_t result;result=fork (); if (result==-1) {printf ("fork error!\n");} else if (result==0) {printf ("in child ' process PID is%d \ returned value is%d \ n", getpid (), result);} Else{printf ("In Father process PID is%d \ n The return value is%d \ n \ nthe", getpid (), result);} return result;}


Run as follows:



2. Vfork ():
Vfork is another system call that Linux provides to generate a child process.
the difference from fork: Vfork does not copy all of the parent process to the child process, but only uses the copy pointer method to share the child process and the parent process's resources.

Because a new process is typically created to exec a new program, Vfork does not produce a copy of the parent process, which can improve efficiency.
Vfork creates a child process like fork, but it does not completely copy the address space of the parent process into the child process because the child process calls exec (or exit) immediately.

However, before the child process calls exec or exit, it runs in the space of the parent process.
Vfork guarantees that the child process runs before the parent process, and the parent process can be scheduled to run only if the child process calls exec or exit.
A child process created with vfork () cannot be returned with return, only exit with exit () or _exit (). A child process created with fork () can be returned with a return.



3. Compare the fork () and vfork () functions to see the difference between

(1) Call the fork () function:

#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h>int main (void ) {    pid_t result;   int  data=5;  result = fork (); /* Call the Fork () function */    if (result = =  -1)/* First error handling *          /printf ("Fork error\n");  else if (result = = 0)/* The return value of 0 represents the */{data++ of the child process;           printf ("data=%d,child\ ' s pid=%d\n", Data,getpid ());}   else/* The return value greater than 0 represents the parent process */       {data++;                 printf ("Data=%d,father\ ' s pid=%d\n", Data,getpid ());}   Exit (1);  }

Run:



(2) Call the Vfork () function:

#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h>int main (void ) {    pid_t result;   int  data=5;  result = Vfork (); /* Call the Fork () function */    if (result = =  -1)/* First error handling *          /printf ("Fork error\n");  else if (result = = 0)/* return value 0 for child process */{  data++;             printf ("data=%d,child\ ' s pid=%d\n", Data,getpid ());}   else/* The return value greater than 0 represents the parent process */       {   data++;                   printf ("Data=%d,father\ ' s pid=%d\n", Data,getpid ());}   Exit (1);  }
Run:


Little talk process: Linux Process Control programming (fork, Vfork)

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.