【发布时间】:2013-03-26 17:20:42
【问题描述】:
我很困惑。据说,基于 man 和许多其他来源,如下所示: Return code when OS kills your process wait(&status) 应该可以让我获得子进程的退出状态或返回值?
那 2 段 sn-ps 代码应该可以让我看到它的子节点的退出值,然后打印出来。 子进程函数:
int childFunction(char in[],char logPath[]){
FILE *logFile= fopen( logPath, "a" );
if(logFile==NULL)
return 1;
int c=system(in);
fclose(logFile);
return(c);
}
和主要的:
{...some unimportant code before this}
result= fork();
if(result==0){
exit(childFunction(inLine,logPath));
}
else if(result>0){
int status=0;;
int c=(int)waitpid(-1,&status,0);
printf("a:%d b:%d\n",status, WIFEXITED(status));
else
return -1;
i=0;
我尝试过等待,休眠一段时间,退出,返回,并阅读手册页几次。要么我对这个功能的理解存在基本错误,要么看了 4 小时后我根本看不到它。
已解决
出于某种原因,我绝对不明白,如果您将 childFunction 中的 return(c) 更改为 if(c!=)return(1);else return(0) 它将起作用。不知道为什么。
解决了 2
好吧,现在我想我知道为什么了。看,似乎返回调用或等待将状态减少到 8 个最高有效位 (256)。这意味着什么?这意味着,如果您发送普通 int,则使用第一位,而丢弃后 8 位。同时,当我指定return (1) 时,编译器会自动将int“缩短”为short int。解决方案是返回一个短数字,或者像我在之前的“已解决”评论中所做的那样。
【问题讨论】: