1

I'm looking for a way to determine whether or not the function execvp succeeded or failed. I do know that if it returns then it has failed, but I'm looking for a case in which the command launched from execvp has failed. Such as in the case where "ls" is trying to list a non-existent folder. From this I plan to add support for logic operators (e.g. &&, ||). Thanks.

else {
    int status;
    if (wait(&status) < 0) {
        perror("wait failed");
        exit(0);
    }
    if (status == 0) {
        success = true;
    }
    else {
        success = false;
    }
}
xythyl
  • 13
  • 5

1 Answers1

3

You need to first fork() a new process, then have that new process call execvp. The parent process should then call wait(), which will allow it to retrieve the exit status of the command you ran (ls, in this case).

When checking the return status retrieved from wait(), be sure to use WIFEXITED() to ensure the child exited normally, and use WEXITSTATUS() to extract the exit status.

pid_t pid = fork();
if (pid == -1) {
    perror("fork failed");
    exit(1);
} else if (pid == 0) {
    execlp("/bin/ls","ls","-l","xyz",NULL);
    perror("exec failed");
    exit(1);
} else {
    int status;
    pid = wait(&status);
    if (WIFEXITED(status)) {
        printf("pid %d exited with status %d\n", pid, WEXITSTATUS(status));
    } else {
        printf("pid %d exited abnormally\n"
    }
}
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Right now I have this, at the end of my checks to see if fork failed. But I don't think I'm looking for the right information from status. `else if (c_pid > 0) { pid = waitpid(c_pid, &status, 0); if (pid == -1) {perror("wait failed"); exit(0); } if (status == 0) { success = true; } success = false; /* if ((pid = wait(&status)) < 0) { perror("wait..."); exit(1); }*/ }` – xythyl Nov 03 '15 at 00:57
  • @xythyl Update your question with your code. It's impossible to read within a comment. – dbush Nov 03 '15 at 00:58
  • Thank you! Also, how to I properly post code on here? For some reason it didn't hold any of the formatting. – xythyl Nov 03 '15 at 01:04
  • @xythyl Paste the code into your question, then press the "`{}`" button at the top of the edit window to format it. – dbush Nov 03 '15 at 01:06
  • How does `wait` retrieve a positive status? According to [this](https://stackoverflow.com/questions/13710003/execvp-fork-how-to-catch-unsuccessful-executions#comment18829737_13710132) it doesn't seem like wait is actually able to determine a successful execvp or not. – Pro Q Nov 24 '18 at 12:57