简体   繁体   English

程序控制如何在fork调用之间切换

[英]how does the program control switch between fork calls

I have recently started understanding fork() system call and I have written below program. 我最近开始了解fork()系统调用,并且在下面的程序中进行了编写。 The doubt that I have in below program is in its output. 我在下面的程序中存在的疑问在于它的输出。 why does the program prints only first ten lines of the parent printf and then moves to print statement in child printf and again move back to print statements in parent printf. 为什么程序只打印父printf的前十行,然后移至子printf中的print语句,然后又移回到父printf中的print语句。 how does this work? 这是如何运作的?

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

int main()
{
    pid_t newpid;
    int i =0;

    newpid=fork();
    if(newpid==0)
    {
        for(i=0;i<10;i++)
        {
            printf("child process pid %d number %d \n", newpid,i);
        }
    }
    else
    {

        for(i=0;i<20;i++)
        {
            printf("parent process pid %d number %d \n", newpid,i);
        }

    }
    return 0;
}

Output: 输出:

parent process pid 9224 number 0
parent process pid 9224 number 1
parent process pid 9224 number 2
parent process pid 9224 number 3
parent process pid 9224 number 4
parent process pid 9224 number 5
parent process pid 9224 number 6
parent process pid 9224 number 7
parent process pid 9224 number 8
parent process pid 9224 number 9
child process pid 0 number 0
parent process pid 9224 number 10
parent process pid 9224 number 11
parent process pid 9224 number 12
parent process pid 9224 number 13
parent process pid 9224 number 14
parent process pid 9224 number 15
child process pid 0 number 1
parent process pid 9224 number 16
child process pid 0 number 2
parent process pid 9224 number 17
child process pid 0 number 3
parent process pid 9224 number 18
parent process pid 9224 number 19
child process pid 0 number 4
child process pid 0 number 5
child process pid 0 number 6
child process pid 0 number 7
child process pid 0 number 8
child process pid 0 number 9

By means of fork() you are altogether creating a new process with its own address space. 通过fork(),您可以使用自己的地址空间创建一个新进程。 This is child process. 这是子进程。 Parent is the one which created the child. 父母是创造孩子的人。 They share the same code though and the output terminal. 它们虽然共享相同的代码,但它们共享输出终端。 They get independently scheduled to run by the operating system. 它们被独立调度为由操作​​系统运行。 Hence you cannot predict in what order the parents print and child's print would be seen.And they certainly won't be in order and that's why you see the prints interleaved. 因此,您无法预测将以何种顺序查看父母和孩子的印刷品,而他们肯定不会按顺序排列,这就是为什么您看到印刷品交错的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM