简体   繁体   English

在循环中运行fork会产生意外结果(测量过程切换时间)

[英]Running fork inside a loop produces unexpected results (measuring process switch time)

I am writing a program to measure the time it takes to perform a process switch. 我正在编写一个程序,以测量执行过程切换所需的时间。 In order to do this I am having a parent write one byte messages to its child and the child read it. 为了做到这一点,我让父母给孩子写一个字节的消息,然后孩子读它。

My problem is in this loop: 我的问题在这个循环中:

for(i=0; i<2; i++)
{
    if(fork()==0) //child process, read
    {
        close(pipefd[1]);
        read(pipefd[0]);
        close(pipefd[0]);
    }

    else //parent process
    {
        close(pipefd[0]);
        write(pipefd[1]);
        close(pipefd[0]);
    }
}

In order to test to see how often the fork was hitting the parent and child I put a printf statement in, and I got around 15 statements printed to the screen. 为了测试看叉子多长时间击中父母和孩子,我输入了一个printf语句,我在屏幕上打印了大约15条语句。 How this is possible considering the loop should only run twice? 考虑到循环应该只运行两次,这怎么可能?

This is because each child process is going to create other processes. 这是因为每个子进程都将创建其他进程。

After the if block is executed, each child will return at the beginning of the loop and fork() again, until i == 2 in all child processes. 执行if块之后,每个子进程将在循环的开头再次返回,并再次fork() ,直到所有子进程中的i == 2为止。

Edit : 编辑:

In order to avoid that, I suggest to use something like this : 为了避免这种情况,我建议使用以下方法:

if(fork() == 0)
{
    //Do stuff
    break;
}

Maybe this is not the most elegant way, but it should work. 也许这不是最优雅的方法,但它应该起作用。

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

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