forks in C - exercise

Posted by Zka on Stack Overflow See other posts from Stack Overflow or by Zka
Published on 2010-03-22T16:12:15Z Indexed on 2010/03/22 16:21 UTC
Read the original article Hit count: 368

Filed under:
|
|
|

I try to repeat and learn more advanced uses and options when cutting trees with forks in the jungle of C. But foolishly I find an example which should be very easy as I have worked with forks before and even written some code, but i can't understand it fully.

Here comes :

main() {
    if (fork() == 0) {
        if (fork() == 0) {
            printf("3");
        }
        else if ((wait(NULL)) > 0) {
            printf("2");
        }
    }
    else {
        if (fork() == 0) {
            printf("1");
            exit(0);
        }
        if (fork() == 0) {
            printf("4");
        }
    }
    printf("0");
    return 0;
}

Possible solutions are :

  1. 3201040
  2. 3104200
  3. 1040302
  4. 4321000
  5. 4030201
  6. 1403020

where 2, 5 and 6 are correct answers.

First of all, shouldn't there be four zeroes in the output? Second... How does one come to the solution at all? Been doing this on paper for almost an hour and I'm not even close to understanding why the given solution are more correct than the false ones (except for nr3 as it can't end with 2 since a 0 must follow).

Anyone with his forks in check who can offer some good explanation?

© Stack Overflow or respective owner

Related posts about c

    Related posts about fork