1

我有以下代码。

我的问题在代码中

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

1 回答 1

4

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

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

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

阅读手册页以wait获取更多信息。

于 2012-11-23T16:07:21.393 回答