如何在fork()中获取execvp的错误?

时间:2012-11-23 16:00:06

标签: c fork execvp

我有以下代码。

我的问题在于代码

     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?
          ......
    }

1 个答案:

答案 0 :(得分:4)

子项的退出状态由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了解更多信息。