为什么对于给定的输入,下面代码的答案总是 32?
我预计是400
代码应该从子进程获取输入并将其传递给父进程并在父进程中打印。
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(){
pid_t p=fork();
if(p>0){
int x=-1;
wait(&x);
printf("sum: %d",x/255);
}else{
int sum=400,i;
int n,x;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&x);
sum+=x;
}
exit(sum);
}
return 0;
}
输入:
4
100 100 100 100
最佳答案
两个问题。首先,exit
(如联机帮助页中明确说明)将您传递给它的状态截断为在 0 到 255 (0377) 范围内
and the value of status & 0377 is returned to the parent
其次,您没有正确使用 wait
返回的值。要获取 child 的 exit
值,您需要使用 WEXITSTATUS(x)
,它返回值的最低有效 8 位,这与执行 x 相同& 255
。
无论哪种方式,您传回 sum
值的方法都不会按原样工作 - 您最好研究一下 pipe
的工作原理。
关于c - wait() 和 exit() 调用的错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48588125/