How to get error of execvp in the fork()?

不问归期 提交于 2019-12-02 15:22:05

问题


I have the following code.

My question is in the code

     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:


The exit status of the child is provided by the wait function, in the status variable.

You get the exit status by using the WEXITSTATUS macro, but only if the program exited normally (i.e. called exit or returned from its main function):

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

Read the manual page for wait for more information.



来源:https://stackoverflow.com/questions/13532391/how-to-get-error-of-execvp-in-the-fork

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!