Q:

Catch exit code of external program in c++

I am running an external program with the command execvp, now I want to catch the exit code of the external program and if possible get the PID of it.
Is there anyway possible?(I know I can read $? in ubuntu and use ps faxu but these are dirty ways for that)

A:

The exec* functions does not return when the program has successfully run, so you can't get the return code via execvp.  However, if you use fork/wait, you could get the exit code from the status code in the wait* functions:
int status;
if (wait(&status) != -1) {   // similar for waitpid, wait4, etc.
    if (WIFEXITED(status)) {
        exit_code = WEXITSTATUS(status);
    } else {
        // handle other conditions, e.g. signals.
    }
} else {
    // wait failed.
}

You could check the example of in the man page of wait(2).

