简体   繁体   English

使用printf检查过程控制

[英]Checking process control using printf

Consider the following C code: 考虑以下C代码:

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. 所有进程都会运行到完成状态,并且printf是原子的,并且在打印其参数之后但在返回之前调用fflush(stdout)。

List individual digits that can be emitted by a call to printf. 列出可以通过调用printf发出的单个数字。

The correct answer is 1 2 3 4 5 6. 正确答案是1 2 3 4 5 6。

However, I can't see why. 但是,我不明白为什么。 First, what are the possible outputs of WEXITSTATUS? 首先,WEXITSTATUS的可能输出是什么? if all processes run to completion, won't that be always equal to 0? 如果所有过程都完成了,那不是总是等于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? 此外,为什么不能输出0,如果counter == 0并且WEXITSTATUS都输出0,那么counter最终将为0?

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. 我几乎可以肯定,最后一个print语句的结果是不确定的,但是从本质上讲,您永远不会得到零,因为counter永远不会为零,因为孩子永远不会返回零。 If counter was zero, then it wouldn't have forked in the first place. 如果counter为零,那么它就不会叉出来。

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; 在计数器4、2和1中,该fork被调用了3次。由于在counter/=2;之后没有printf语句,所以不打印0 counter/=2; and the while loop eventually exit after the counter getting 0. 并且while循环最终在计数器变为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 WEXITSTATUS的可能输出可以是WEXITSTATUS和0。但是只有两个waitpid ,第二个printf的输出应该是6,因为只有两个waitpid调用将仅等待4和2。因此,第二个printf输出应为6。如果再添加一个

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

the output should be 7. 输出应为7。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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