There are too many processes in the forks

Asked 2 years ago, Updated 2 years ago, 29 views

When you run the following source code: As I intended, there should be 6 moles There are 8 pictures. Why is that?

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

int main(void)
{
    int i;
    for(i = 0; i < 2; i++)
    {
        fork();
        printf(".");
    }
    return 0;
}

c c++ fork

2022-09-21 16:50

1 Answers

Sometimes forks() are more than you think. Write the code flow on the paper and follow it

There is only one process (1) at first. When process 1 enters the for statement and executes fork(), a second process (2) is created. Both Process 1 and Process 2 now output points.

When process 1 and process 2 turn the for statement second (i=1), execute forks() Create process 3 and process 4, respectively. Each of the four processes will now dot once.

Then the total points should be marked (2+4) times. But why are there eight dots?

Because of printf(). printf() buffers output. So in the first loop (when there are two processes), the fact point remains in the buffer without being output.

At this time, when fork() copies the current process, the buffer is also copied When fork() of the second loop creates processes 3 and 4, the contents in the buffer are also copied. So there's one dot in each buffer of the four processes. Now if you run printf() one more time, the buffers for the four processes now contain two dots each At the end of the program, the processes empty the buffer and make a total of eight dots.

To solve this problem, do fflush(stdout) after printf()

alt text


2022-09-21 16:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.