Process of programming in Linux (II): fork function Summary

Source: Internet
Author: User

1. Fork system call

Contains the header file <sys/types. h> and <unistd. h>
Function: create a sub-process
Function prototype
Pid_t fork (void );
Parameter: No parameter.
Return Value:
If a child process is successfully created, the child process ID is returned for the parent process.
If a child process is successfully created, the return value is 0 for the child process.
-1 indicates creation failed.


(1) The child process obtained by using the fork function inherits the address space of the entire process from the parent process, including: process context, process stack, memory information, open file descriptor, signal control settings, process priority, process group number, current working directory, root directory, resource limit, control terminal, etc.



(2) The difference between a child process and a parent process is:
1. The lock set by the parent process. The child process does not inherit
2. The process IDs and parent process IDs are different.
3. Pending alarms of sub-processes are cleared;
4. the pending Signal Set of the sub-process is set to an empty set.


(3) Notes for fork system calls

After the fork system is called, the Parent and Child processes are executed alternately.
If the parent process exits first and the child process has not exited, the parent process of the child process will become the INIT process. (Note: Any process must have a parent process)
If the sub-process exits first and the parent process has not exited, the sub-process must wait until the sub-process is captured and exited. Otherwise, the sub-process becomes a zombie process.

When a child process exits, it sends a sigchld signal to the parent process. You can ignore the signal or use the signal processing function to receive and process the child process.


(4) copy on write

If multiple processes want to read copies of their own resources, replication is unnecessary.
Each process only needs to save a pointer to this resource.
If a process needs to modify the "copy" of its own resource, it will copy that resource. This is what replication means during writing.

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

If vfork () is used, the parent-child process shares the same address space before exec is called. It does not copy data like fork ().


(5) The Parent and Child processes share files after fork


The child process inherits the file descriptor opened by the parent process. Therefore, the reference count of each opened file is 2.


(6) fork and vfork

Before fork implements copy on write. UNIX designers are concerned about the address space waste caused by not executing exec immediately after fork, so vfork system calls are introduced.
Vfork has a restriction. The Subprocess must immediately execute the _ exit or exec function.
Even if fork implements copy on write, the efficiency is not as high as vfork, but we do not recommend vfork, because almost every vfork implementation has more or less problems.


Example program:

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*************************************** **********************************
> File name: process_fork.c
> Author: Simba
> Mail: dameng34@163.com
> Created time: sat 23 Feb 2013 02:34:02 pm CST
**************************************** ********************************/
/* If the parent process exits first and the child process has not exited, the parent process of the child process will become the INIT process. (Note: Any process must have a parent process)
* If the child process exits first and the parent process has not exited, the child process must wait until the child process is captured and exited,
* Otherwise, the sub-process becomes a zombie process.
*/
# Include <sys/types. h>
# Include <sys/STAT. h>
# Include <unistd. h>
# Include <fcntl. h>
# Include <stdio. h>
# Include <stdlib. h>
# Include <errno. h>
# Include <string. h>
# Include <signal. h>

# Define err_exit (m )\
Do {\
Perror (m );\
Exit (exit_failure );\
} While (0)

Int main (INT argc, char * argv [])
{
Signal (sigchld, sig_ign); // prevents zombie processes and ignores sigchld signals.
Printf ("before fork pid = % d \ n", getpid ());
Int FD;
FD = open ("test.txt", o_wronly );
If (FD =-1)
Err_exit ("Open error ");

Pid_t PID;
PID = fork (); // copy on write when writing, read-only code segments can be shared
/* If vfork () is used, the Parent and Child processes share the same address space before exec is called,
* It does not copy like fork */
If (pid =-1)
Err_exit ("fork error ");

If (pid> 0)
{
Printf ("this is parent \ n ");
Printf ("parent pid = % d child pid = % d \ n", getpid (), pid );
Write (FD, "parent", 6); // The Parent and Child processes share a file table.
Sleep (10 );
}

Else if (pid = 0)
{
Printf ("this is child \ n ");
Printf ("Child pid = % d parent pid = % d \ n", getpid (), getppid ());
Write (FD, "child", 5 );
}

Return 0;
}

The test output is as follows:

Simba @ Ubuntu :~ /Documents/code/linux_programming/apue/process $./process_fork
Before fork pid = 2572
This is parent
Parent pid = 2572 child pid = 2573
This is child
Child pid = 2573 parent pid = 2572
Simba @ Ubuntu :~ /Documents/code/linux_programming/apue/process $ cat test.txt
Parent
Child
Simba @ Ubuntu :~ /Documents/code/linux_programming/apue/process $

It can be seen that, for the purpose of sharing a file table, the original file is also shared, and the content of the parent program printed into the test.txt file is followed, not from the beginning.


Reference: apue


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.