How to run two child processes simultaneously in C?

11,363

Solution 1

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.

Solution 2

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
Share:
11,363
Jordan Scales
Author by

Jordan Scales

Updated on June 04, 2022

Comments

  • Jordan Scales
    Jordan Scales almost 2 years

    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;
    }