How to run two child processes simultaneously in C

2019-04-12 07:36发布

So I'm getting into Concurrent Programming, but for some reason I can't even get the basics to work. I have a file called fork.c, which contains a method main. In this method main I fork twice, into child processes 1 and 2.

In child 1, I print the character 'A' 50 times.

In child 2, I print the character 'B' 50 times.

When I run my code, I get the output AAAAA...AAAABBBBBB....BBBBBB. But never something like ABABABABABABAB.... In fact, sometimes I even get BBBBB....BBBBAAAA....AAAAA.

So why am I experiencing this behavior? Perhaps I'm going about it completely wrong.

#include <stdlib.h>
#include <stdio.h>

void my_char(char n) {
    write(1, &n, 1);
}

int main() {
    int status;
    pid_t child1, child2;

    if (!(child1 = fork())) {
        // first childi
        int a;
        for (a = 0; a < 50; a++) {
            my_char('A'); 
        }
        exit(0);
    } else if (!(child2 = fork())) {
        // second child
        int a;
        for (a = 0; a < 50; a++) {
            my_char('B');
        }
        exit(0);
    } else {
        // parent
        wait(&child1);
        wait(&child2);
        my_char('\n');
    }

    return 0;
}   

2条回答
够拽才男人
2楼-- · 2019-04-12 08:09

They are running concurrently, but the processes end almost immediately after being started. In other words, they're too short to actually get any real overlap.

EDIT:

The time needed to start another process is longer than the time it takes to run them. Therefore the chance of overlap is small. (there are also buffering issues which I'll omit)

You need each process to do more work than that. Try printing more than 50. Printing more than 10000 will probably be enough.

查看更多
来,给爷笑一个
3楼-- · 2019-04-12 08:23

I think this is much easier to figure how fork() works:

#include <stdlib.h>
#include <stdio.h>

int main() {
    pid_t child1, child2;
    printf("Start\n");
    if (!(child1 = fork())) {
        // first childi
        printf("\tChild 1\n");
        sleep(5);
        exit(0);
    } else if (!(child2 = fork())) {
        // second child
        printf("\tChild 2\n");
        sleep(5);
        exit(0);
    } else {
        // parent
        printf("Parent\n");
        wait(&child1);
            printf("got exit status from child 1\n");
        wait(&child2);
            printf("got exit status from child 2\n");
    }

    return 0;
}

...and here is the output:

    Start
        Child 1
    Parent
        Child 2
    got exit status from child 1
    got exit status from child 1
查看更多
登录 后发表回答