首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >fork/exec/waitpid问题

fork/exec/waitpid问题
EN

Stack Overflow用户
提问于 2012-12-06 09:25:59
回答 1查看 9.4K关注 0票数 5

我试图通过检查waitpid()的结果来确定执行是否失败。但是,即使当我运行一个我知道失败的命令并将问题写入stderr时,下面的检查也不会注册。这段代码可能出了什么问题?

谢谢你的帮助。

代码语言:javascript
复制
pid_t pid;  // the child process that the execution runs inside of.
int ret;      // exit status of child process.

child = fork();

if (pid == -1)
{
   // issue with forking
}
else if (pid == 0)
{
   execvp(thingToRun, ThingToRunArray); // thingToRun is the program name, ThingToRunArray is
                                        //    programName + input params to it + NULL.

   exit(-1);
}
else // We're in the parent process.
{
   if (waitpid(pid, &ret, 0) == -1)
   {
      // Log an error.
   }

   if (!WIFEXITED(ret)) // If there was an error with the child process.
   {

   }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-06 09:29:43

如果waitpid出现错误,则waitpid仅返回-1。也就是说,如果您给它一个错误的pid,或者它被中断,等等。如果孩子有一个失败的退出状态,waitpid将成功(返回pid)并设置ret以反映孩子的状态。

要确定子进程的状态,请使用WIFEXITED(ret)WEXITSTATUS(ret)。例如:

代码语言:javascript
复制
if( waitpid( pid, &ret, 0 ) == -1 ) {
  perror( "waitpid" );
} else if( WIFEXITED( ret ) && WEXITSTATUS( ret ) != 0 ) {
    ; /* The child failed! */
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13735501

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档