fork()系统调用及陷阱

Posted miaoxiong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fork()系统调用及陷阱相关的知识,希望对你有一定的参考价值。

Fork System Call

The fork system call is used to create a new processes. The newly created process is the child process. The process which calls fork and creates a new process is the parent process. The child and parent processes are executed concurrently.

But the child and parent processes reside on different memory spaces. These memory spaces have same content and whatever operation is performed by one process will not affect the other process.

When the child processes is created; now both the processes will have the same Program Counter (PC), so both of these processes will point to the same next instruction. The files opened by the parent process will be the same for child process.

The child process is exactly the same as its parent but there is difference in the processes ID’s:

  1. The process ID of the child process is a unique process ID which is different from the ID’s of all other existing processes.
  2. The Parent process ID will be the same as that of the process ID of child’s parent.

Properties of Child Process

The following are some of the properties that a child process holds:

  1. The CPU counters and the resource utilizations are initialized to reset to zero.
  2. When the parent process is terminated, child processes do not receive any signal because PR_SET_PDEATHSIG attribute in prctl() is reset.
  3. The thread used to call fork() creates the child process. So the address of the child process will be the same as that of parent.?
  4. The file descriptor of parent process is inherited by the child process. For example the offset of the file or status of flags and the I/O attributes will be shared among the file descriptors of child and parent processes. So file descriptor of parent class will refer to same file descriptor of child class.
  5. The open message queue descriptors of parent process are inherited by the child process. For example if a file descriptor contains a message in parent process the same message will be present in the corresponding file descriptor of child process. So we can say that the flag values of these file descriptors are same.
  6. Similarly open directory streams will be inherited by the child processes.
  7. The default Timer slack value of the child class is same as the current timer slack value of parent class.?

Properties that are not inherited by Child process

The following are some of the properties that are not inherited by a child process:

  1. Memory locks
  2. The pending signal of a child class is empty.
  3. Process associated record locks (fcntl())
  4. Asynchronous I/O operations and I/O contents.
  5. Directory change notifications.
  6. Timers such as alarm(), setitimer() are not inherited by the child class.

fork() in C

There are no arguments in fork() and the return type of fork() is integer. You have to include the following header files when fork() is used:

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

 

When working with fork(), <sys/types.h> can be used for type pid_t for processes ID’s as pid_t is defined in <sys/types.h>.

The header file <unistd.h> is where fork() is defined so you have to include it to your program to use fork().

The return type is defined in <sys/types.h> and fork() call is defined in <unistd.h>. Therefore, you need to include both in your program to use fork() system call.

Syntax of fork()

The syntax of fork() system call in Linux, Ubuntu is as follows:

pid_t fork(void);

 

In the syntax the return type is pid_t. When the child process is successfully created, the PID of the child process is returned in the parent process and 0 will be returned to the child process itself.

If there is any error then -1 is returned to the parent process and the child process is not created.

  No arguments are passed to fork().

Example 1: Calling fork()

Consider the following example in which we have used the fork() system call to create a new child process:

CODE:

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

int main()

    fork();
    printf("Using fork() system call\n");
    return 0;

 

OUTPUT:

Using fork() system call
Using fork() system call

 

技术图片

In this program, we have used fork(), this will create a new child process. When the child process is created, both the parent process and the child process will point to the next instruction (same Program Counter). In this way the remaining instructions or C statements will be executed the total number of process times, that is 2n times, where n is the number of fork() system calls.

So when the fork() call is used one time as above (21 = 2) we will have our output 2 times.

Here when the fork() system call is used, the internal structure will look like:

技术图片

Consider the following case in which the fork() is used 4 times:

CODE:

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

int main()

    fork();
    fork();
    fork();
    fork();
    printf("Using fork() system call");
    return 0;

 

Output:

Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call
Using fork() system call

 

技术图片

Now the total number of process created are 24 = 16 and we have our print statement executed 16 times.

Example 2: Testing if fork() was successful

In the following example we have used the decision making construct to test the value (int) returned by fork(). And the corresponding messages are displayed:

CODE:

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

int main()

    pid_t p;
    p = fork();
    if(p==-1)
    
        printf("There is an error while calling fork()");
    
    if(p==0)
    
        printf("We are in the child process");
    
    else
    
        printf("We are in the parent process");
    
    return 0;

 

OUTPUT:

We are in the parent process
We are in the child process

 

技术图片

In the above example we have used the type pid_t which will store the return value of fork(). fork() is called on line:

p = fork();

 

So the integer value returned by fork() is stored in p and then p is compared to check if our fork() call was successful.

When the fork() call is used and child is created successfully, the id of child process will be returned to parent process and 0 will be returned to the child process.The ID of child process in Parent process will not be the same as the ID of child process in child process itself. In child process the ID of child process will be 0.

With this tutorial you can see how to get started with the fork system call in linux.

 

原文摘抄自:https://linuxhint.com/fork-system-call-linux/

 

How to make parent wait for all child processes to finish?

pid_t child_pid, wpid;
int status = 0;

//Father code (before child processes start)

for (int id=0; id<n; id++) 
    if ((child_pid = fork()) == 0) 
        //child code
        exit(0);
    


while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes 

//Father code (After all child processes end)

wait waits for a child process to terminate, and returns that child process‘s pid. On error (eg when there are no child processes), -1 is returned. So, basically, the code keeps waiting for child processes to finish, until the waiting errors out, and then you know they are all finished.

 

摘抄自:https://stackoverflow.com/questions/19461744/how-to-make-parent-wait-for-all-child-processes-to-finish

 

CoW (copy on write)

To save time on fork, the kernel only duplicate its mapping. For example we have 100 pages mapping for the array , the kernel will duplicate the TLB entries and change all the mapping to read only. If both processes only read, they work with shared memory but when one process try to write, it creates a page fault, the kernel trap handler copy the page and change the permission to read-write returning the program counter to the previous statement to try again.

If we measure the time of the first assignment , we will get a longer time:

To test this using Ubuntu 64 bit we add a simple assembly function

As you can see from the output , the first time we write take 3 times longer as a result of a page fault.

 

Fail to fork?

fork fails in some situations: if we reached the maximum user processes allowed (see ulimit -a) , out of memory, no MMU and more (see man page)

It also fails if the parent process consume more than 50% of the system memory. Let take an example:

The above behaviour can create a strange bug in the following situation:

  • The parent fill a 200MB array and fork
  • On fork, the system has 250MB free – fork returns successfully
  • As a result of Copy on write mechanism , the memory is not consumed
  • Another process consume 200MB
  • The child process access the array elements and while trying to handle the page faults the kernel crashed

Lets test it on Qemu image with 512MB:

 

技术图片

Code Example:

Run this program and after fork:

技术图片

We can see the only 200MB consumed. Now run a simple program to consume more memory:

void main(void)

    int x,status;
    int arr1[52000000];
    puts("bye");
    memset(arr1,0,sizeof(arr1));
    sleep(1000);

 

and check again:

技术图片

Now the child write to 4MB every 30 seconds and make a copy of the pages , when it will reach the system limit (100MB only) we will see a kernel oops:

We can see the oops generated on a page fault (do_page_fault)

To avoid such cases we need to pre fault the array (read and write its content at least one element per page) immediately after fork.

 

Files are not duplicated on fork

It is important to understand that file descriptor object are not duplicated on fork. In this way we can share resources between the child and the parent. All the anonymous objects (pipes, shared memory, etc.) can only be shared using the file descriptor. One way (the easy way) is declaring the resource before forking and the other way is sending the file descriptor using unix domain socket. If we open a regular file the child and the parent are using the same kernel object i.e. position, flags, permission and more are shared:

Example:

We open a file, read 29 chars on the parent and 29 chars on the child, the parent update the position so the child is reading where the parent ended:

Output:

 

以上是关于fork()系统调用及陷阱的主要内容,如果未能解决你的问题,请参考以下文章

Android拉起系统相机拍照的两种方式及陷阱

Android拉起系统相机拍照的两种方式及陷阱

Linux 系统调用 —— fork 内核源码剖析

操作系统实验2:fork()系统调用

Linux 内核进程管理 ( 进程相关系统调用源码分析 | fork() 源码 | vfork() 源码 | clone() 源码 | _do_fork() 源码 | do_fork() 源码 )

fork 系统调用的执行过程与调试