execvp/fork — how to catch unsuccessful executions?

前端 未结 3 975
臣服心动
臣服心动 2021-02-02 04:18

Right now I\'m writing a C program that must execute a child process. I\'m not doing multiple child processes simultaneously or anything, so this is fairly straightforward. I am

3条回答
  •  情歌与酒
    2021-02-02 04:38

    wait(2) gives you more than just the exit status of the child process. In order to get the real exit status, you need to use the WIFEXITED() macro to test if the child exited normally (as opposed to abnormally via a signal etc.), and then use the WEXITSTATUS() macro to get the real exit status:

    wait(&status);
    if(WIFEXITED(status))
    {
        if(WEXITSTATUS(status) == 0)
        {
            // Program succeeded
        }
        else
        {
            // Program failed but exited normally
        }
    }
    else
    {
        // Program exited abnormally
    }
    

    In order for execvp(3) to run a program in the current directory, you either need to add the current directory to your $PATH environment (generally not a good idea), or pass it the full path, e.g. use ./myprogram instead of just myprogram.

提交回复
热议问题