简体   繁体   中英

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)

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) .

Try also int a_number = std::system("/path/to/app")

This sometimes can be used to return the value of an xmessage query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM