我正在尝试配置这个简单代码的输出。但我无法理解。 预期输出是
int main()
{
int val = 5;
if(fork())
wait(&val);
val++;
printf("%d\n", val);
return val;
}
预期输出为
6
7
但是 Linux 给了我
6
1537
请谁能告诉我这段代码背后发生了什么。 我可以预测 return 语句一定有问题。 感谢详细解释。
最佳答案
您唯一要做的就是更改函数wait()的参数值。
int main()
{
int val = 5;
if(fork())
wait(NULL);
val++;
printf("%d\n", val);
return val;
}
您的输出为1537,因为 status() 函数更改了您的变量值。
wait() 的 man 摘录,其中 status 代表函数的参数。
If status is not NULL, wait() and waitpid() store status information in the int to which it points.
祝你好运。
关于c - Linux进程中return语句的真实故事,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29850974/