简体   繁体   中英

WEXITSTATUS always returns 0

I am forking a process and running a wc command using execl . Now under correct arguments, it runs fine, but when I give a wrong file name, it fails, but in both the cases the return value of WEXITSTATUS(status) is always 0.

I believe there is something wrong with what I am doing, but I'm not sure what is. Reading man pages and Google suggests that I should get a correct value as per the status code.

Here is my code:

#include <iostream>
#include <unistd.h>

int main(int argc, const char * argv[])
{
    pid_t pid = fork();
    if(pid <0){
        printf("error condition");
    } else if(pid == 0) {
        printf("child process");
        execl("/usr/bin/wc", "wc", "-l", "/Users/gabbi/learning/test/xyz.st",NULL);
        printf("this happened");
    } else {
        int status;
        wait(&status);

        if( WIFEXITED( status ) ) {
            std::cout << "Child terminated normally" << std::endl;
            printf("exit status is %d",WEXITSTATUS(status));
            return 0;
        } else {     
        }
    }
}

If you supply a name of non existing file to execl() as 1st argument it fails. If this happens the program leaves without returning any specifiy value. So the default of 0 is returned.

You could fix the for example like this:

#include <errno.h>

...

int main(int argc, const char * argv[])
{
  pid_t pid = fork();
  if(pid <0){
    printf("error condition");
  } else if(pid == 0) {
    printf("child process");
    execl(...); /* In case exec succeeds it never returns. */
    perror("execl() failed");
    return errno; /* In case exec fails return something different then 0. */
  }
  ...

You are not passing the file name from argv to the child process

Instead of

 execl("/usr/bin/wc", "wc", "-l", "/Users/gabbi/learning/test/xyz.st",NULL);

Try this,

 execl("/usr/bin/wc", "wc", "-l", argv[1],NULL);

The output I got on my machine

xxx@MyUbuntu:~/cpp$ ./a.out test.txt 
6 test.txt
Child terminated normally
exit status is 0

xxx@MyUbuntu:~/cpp$ ./a.out /test.txt 
wc: /test.txt: No such file or directory
Child terminated normally
exit status is 1

This was an xcode issue, running from console works fine. I am a Java guy, doing some assignments in CPP. Nevertheless, it might come handy to someone getting stuck at similar issue.

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