简体   繁体   中英

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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