In fork (), which will be run first, parent or child?

When the following code is executed, I understand that the parent and child will start in parallel right after calling fork ().

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

int main(void)
{
    int pfds[2];
    char buf[30];

    pipe(pfds);

    if (!fork()) {
        printf(" CHILD: writing to the pipe\n");
        write(pfds[1], "test", 5);
        printf(" CHILD: exiting\n");
        exit(0);
    } else {
        printf("PARENT: reading from pipe\n");
        read(pfds[0], buf, 5);
        printf("PARENT: read \"%s\"\n", buf);
        wait(NULL);
    }

    return 0;
}

This means that the child will perform:

printf(" CHILD: writing to the pipe\n"); 

And the parent will execute

printf("PARENT: reading from pipe\n");

Parallel.

For those not familiar with C, in sh:

$ sh -c 'echo CHILD & echo PARENT; wait'
PARENT
CHILD

So, I ran this code on one core of the processor, as well as on a dual core, but noticed that the parent is always printed first. Since the two are parallel, it is reasonable to expect a random order. But this does not happen. Why is this so?

+4
source share
2 answers

Apparently, any scheduler you use solves, and it can change.

, , , . -, , , .

+3

, , , :

if (!fork()) {
        printf(" CHILD: writing to the pipe\n");
        write(pfds[1], "test", 5);
        printf(" CHILD: exiting\n");
        exit(0);
    } else {
        printf("PARENT: reading from pipe\n");
        read(pfds[0], buf, 5);
        printf("PARENT: read \"%s\"\n", buf);
        wait(NULL);
    }

fork , else printf. , , . , read() .

, . xv6:

, , , ; 0, .

xv6 Linux, UNIX. , linux Man :

, (2)         .        (. ), (2) ,         , .        / fcntl (2) F_SETFL,        O_NONBLOCK .

, printf(), write() , , , .

, , read() , , .

,

, , . , , , .

+2

Source: https://habr.com/ru/post/1525411/


All Articles