【问题标题】:How to get error of execvp in the fork()?如何在 fork() 中获取 execvp 错误?
【发布时间】:2012-11-23 16:00:06
【问题描述】:

我有以下代码。

我的问题在代码中

     int main() {

            ....

         if ((uproc.pid = fork()) == -1) {
            return -1;
        }

        if (uproc.pid == 0) {
            /* child */

            const char *argv[3];
            int i = 0;
            argv[i++] = "/bin/sh";
            argv[i++] =  "/my/script.sh";
            argv[i++] = NULL;

            execvp(argv[0], (char **) argv);
            exit(ESRCH);

        } else if (uproc.pid < 0)
            return -1;

        /* parent */
        int status;
        while (wait(&status) != uproc.pid) {
            DD(DEBUG,"waiting for child to exit");
        }

           // If /my/script.sh exit accidentally in some place with error. 
           // can I catch this error right here?
          ......
    }

【问题讨论】:

  • 你通过wait函数进入,它在status变量中。
  • 这可能是对我的问题的回应
  • status 始终为 0。万一没有错误,万一脚本有错误

标签: c fork execvp


【解决方案1】:

孩子的退出状态由wait函数提供,在status变量中。

您可以使用WEXITSTATUS 宏获得退出状态,但前提是程序正常退出(即调用exit 或从其main 函数返回):

if (WIFEXITED(status))
    printf("Child exit status: %d\n", WEXITSTATUS(status));
else
    printf("Child exited abnormally\n");

阅读manual page for wait了解更多信息。

【讨论】:

  • 从 OP 不清楚(“...获取执行的 cmd 的错误 ...”)如果它真的是想要的退出代码。无论如何1+,这就是所有一个人可以得到的。
  • 我的脚本在中间退出并显示消息错误,因为中间有错误。状态返回始终为 0(如果脚本中有错误,而在 cas 中没有)
  • 那么为什么不改变它,让你的脚本只在成功的情况下使用exit 0,并且在任何错误调用exit 时使用不同于0 的参数。 @MohamedKALLEL
  • 要使脚本对由脚本启动的进程的异常终止作出反应,您可以使用trap。可以在此处找到有关使脚本更健壮的有趣文章:davidpashley.com/articles/writing-robust-shell-scripts.html@MohamedKALLEL
猜你喜欢
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 2012-11-22
  • 1970-01-01
相关资源
最近更新 更多