简体   繁体   中英

Checking process control using printf

Consider the following C code:

int main(){
    pid_t pid;
    int status, counter = 4;

    while(counter > 0){
        pid = fork();

        if (pid){
            counter/=2;
        }

        else{
            printf("%d", counter);
            break;
        }
    }
    if (pid){
        waitpid(-1, &status, 0);
        counter += WEXITSTATUS(status);

        waitpid(-1, &status, 0);
        counter += WEXITSTATUS(status);

        printf("%d", counter);
    }
    return counter;
}

All processes run to completion and printf is atomic and calls fflush(stdout) after printing its arguments but before returning.

List individual digits that can be emitted by a call to printf.

The correct answer is 1 2 3 4 5 6.

However, I can't see why. First, what are the possible outputs of WEXITSTATUS? if all processes run to completion, won't that be always equal to 0? Besides, why is 0 not a possible output?If counter == 0 and WEXITSTATUS both output 0, then counter would be 0 in the end no?

I'm almost certain that the results are non-deterministic for the last print statement, but essentially you'll never get zero because counter will never be zero because the child will never return zero. If counter was zero, then it wouldn't have forked in the first place.

The fork is called three times for counter 4, 2, and 1. And 0 is not printed because there is no printf statement after counter/=2; and the while loop eventually exit after the counter getting 0.

The possible outputs of WEXITSTATUS can be 4, 2, 1, and 0. But there is only two waitpid , the output of the second printf should be 6 since there are only two waitpid calls which will wait for only 4 and 2. Therefore the output of the second printf should be 6. If you add one more

waitpid(-1, &status, 0);
counter += WEXITSTATUS(status);

the output should be 7.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM