Linux fork function and vfork function

Source: Internet
Author: User
Tags function prototype

Man vfork:


NAME
Vfork- Create a child process and block parent

Synopsis
#include <sys/types.h>
#include <unistd.h>

pid_t vfork (void);

DESCRIPTION
Standard description
(from Posix.1) The Vfork () function has the same effect as fork (2), except that the behav‐
IOR is undefined if the process created by vfork () either modifies any data other than a
Variable of type pid_t used to store the return value from Vfork (), or returns from the
function in which vfork () is called, or calls any other function before successfully
Calling _exit (2) or one of the exec (3) family of functions.

Linux description
Vfork (), Just like fork (2), creates a child process of the calling process. For details
and return value and errors, see Fork (2).

Vfork () is a special case of Clone (2). It's used to create new processes without copying
The page tables of the parent process. It is useful in performance-sensitive applica‐
tions where a child was created which then immediately issues an EXECVE (2).

Vfork () differs from fork (2) in that the calling thread was suspended until the child ter‐
Minates (either normally, by calling _exit (2), or abnormally, after delivery of a fatal
signal), or it makes a call to Execve (2). Until, the child shares all memory
With its parent, including the stack. The child must not return from the current function
or call Exit (3), and may call _exit (2).

As with fork (2), the child process created by Vfork () inherits copies of various of the
Caller ' s process attributes (e.g., file descriptors, signal dispositions, and current
Working directory); The vfork () call differs only in the treatment of the virtual address
Space, as described above.

Signals sent to the parent arrive after the child releases the parent's memory (i.e.,
After the child terminates or calls Execve (2)).

The method of creating a new process is only called by an existing process to fork () or vfork (), although some processes, such as Init, are created by the kernel as a system-initiated wind.

First, fork
1. Calling methods
#include <sys/types.h>
#include <unistd.h>

pid_t fork (void);
Returned correctly: The process number of the child process is returned in the parent process, and 0 is returned in the child process
Error return: 1

A child process is a copy of the parent process. That is, the child process obtains a copy of the data segment and the stack segment from the parent process , which needs to be allocated new memory, whereas for a read-only snippet, it is usually accessed using the shared Ram method . When Fork returns, both the child process and the parent process begin execution from the point where the fork function is called.
The difference between a parent and a child process is that the return value of fork is different-the return value in the parent process is the process number of the child process, and the child process is 0
2. Purpose of the fork function call
⑴ a process wants to replicate itself, so the parent-child process can execute different pieces of code at the same time.
⑵ process wants to execute another program

Second, vfork
1. Calling methods
Exactly the same as the fork function
#include <sys/types.h>
#include <unistd.h>

pid_t fork (void);
Returned correctly: The process number of the child process is returned in the parent process, and 0 is returned in the child process
Error return: 1

2. Purpose of the Vfork function call
The process created with Vfork is primarily intended to execute an additional program with the EXEC function, which is the same as the second use of fork

The difference between fork and vfork
1. fork to copy the data segment of the parent process, while Vfork does not need to fully copy the data segment of the parent process, and the child process shares the data segment with the parent process before the child process calls exec and exit
2. Fork does not restrict the execution order of the parent-child process, whereas in the vfork call, the child process runs first, the parent process hangs until the child process calls exec or exit, and the order of the parent-child process is no longer restricted

Iv. ending a child process
End Child process without exit (0), instead of using _exit (0). This is because _exit (0) does not perform any operations on the standard I/O stream at the end of the process. Exit (0) closes all standard I/O streams for the process.

Because the child process is unrelated to the run of the parent process, the parent process can run before the child process, or the child process can run before the parent process, so the next segment of the program may have two running results.

#include <stdio.h>#include<sys/types.h>#include<unistd.h>int Global=4;intMain () {pid_t pid; intVari=5; printf ("before fork\n"); if((Pid=fork ()) = =0)    {        Global++; Vari--; printf ("Child changed\n"); }    Elseprintf ("parent did Nog changed\n"); printf ("global=%d,vari=%d\n",Global, vari); }

[Email protected]:~/ms/linux/unp/unpmy/tcpcliserv#./fork1
Before fork
Parent did Nog changed
Global=4,vari=5
[Email protected]:~/ms/linux/unp/unpmy/tcpcliserv# Child changed
Global=5,vari=4

[Email protected] src]#./a.out
Before fork
Child changed
Globa = 5 Vari = 4
Parent did not Changde
Globa = 4 Vari = 5

Vfork The primary purpose of creating a new process is to execute an additional program with the EXEC function, in effect sharing the data segment with the parent process in the run of the child process before exec or exit is called. In the vfork call, the child process runs first, the parent process hangs until the child process calls exec or exit, and after that, the sequence of execution of the parent-child process no longer has a limit.

#include <stdio.h>#include<sys/types.h>#include<unistd.h>int Global=4;intMain () {pid_t pid; intVari=5; printf ("before fork\n"); if((Pid=vfork ()) = =0)    {        Global++; Vari--; printf ("Child changed\n"); _exit (0); }    Elseprintf ("parent did Nog changed\n"); printf ("global=%d,vari=%d\n",Global, vari); Exit (0); }

[Email protected]:~/ms/linux/unp/unpmy/tcpcliserv#./fork2
Before fork
Child changed
Parent did Nog changed
Global=5,vari=4.

(It can be seen from here that the data segment is shared.) )

Reference: http://blog.csdn.net/lingdxuyan/article/details/4996471

Linux c down exit (0); with _exit (0);

#include <unistd.h>#include<stdio.h>#include<stdlib.h>intMainvoid) {pid_t pid;if((Pid=fork ()) ==-1) {printf ("Error"); }Else if(pid==0) {printf ("ok\n"); exit (0);}Else{printf ("Parent Process,output begin\n");p rintf ("Hello Word"); _exit (0);}}

After commissioning you will find no

Hello Word

Exit is to exit the memory in the first output to the file, and _exit this direct exit, eliminate in-memory data;

printf is the standard line output, the "\ n" or write memory is full before the standard output;

We can try to add a lot of I in Hello Word, assuming input 2000 bar (about line output self Google), debugging again found that there will be hello and other characters, this is overflow.

Back to the front, why did not start without hello, although Hello Word before _exit, but you look at the Assembly will find that he just speaks the data exists in memory. There is no real output of speaking data. When we get rid of _exit Hello Word can show. Why is it? This is the compiler's own addition.

As you can see, the _exit function is to stop the process from running, clear its used memory space, and clear its various data structures in the kernel; the exit function does some tricks on these bases and adds several operations to the exit before executing. The most important difference between the exit () function and the _exit () function is that the exit () function checks the opening of the file before calling the exit system, and writes the contents of the file buffer back to the file. That is, "clean I/O buffering" in the figure.

Header file required: Exit: #include <stdlib.h>

_exit: #include <unistd.h>

Function prototype: exit:void exit (int status)

_exit:void _exit (int status)

Function pass-through value: status is an integer parameter that can be used to pass the state at the end of the process. Generally speaking, 0 means the normal end; other values indicate an error and the process is not properly terminated. During actual programming, the parent process can take advantage of the wait system call to receive the return value of the child process, thus making different processing for different situations

Reference: http://blog.csdn.net/lwj103862095/article/details/8640037

Linux fork function and vfork function

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.