gpt4 book ai didi

c - 为什么 "X"可以是输出的最后一个字符?

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:14 24 4
gpt4 key购买 nike

#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
if (fork() == fork()){

fprintf(stderr, "Z");
}
else {
if (waitpid((pid_t)-1,NULL,0)!=-1) {
fprintf(stderr, "Y");

}
else {
fprintf(stderr, "X");
}
}
}

我正在研究这个程序,我发现可以输出“ZYYX”。我不太明白为什么。在我的理解中,一共有四个过程,parent->parent,parent->child,child->parent,child->parent。毫无疑问,child->child 打印 Z。child->parent 在 child->child 打印 Z 之后打印 Y。parent->parent 应该等到 parent->child 打印 X。那么为什么 X 可能是打印为输出的最后一个字符?

最佳答案

我意识到 waitpid 等待任何子进程,所以如果 ZY 已经打印出来,那么 Y 可以立即打印出来,因为它已经等待了“Y”。因此,X 可以打印为最后一个字符。

关于c - 为什么 "X"可以是输出的最后一个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47849574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com