简体   繁体   English

WEXITSTATUS始终返回0

[英]WEXITSTATUS always returns 0

I am forking a process and running a wc command using execl . 我正在分叉进程并使用execl运行wc命令。 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. 现在,在正确的参数下,它可以正常运行,但是当我输入错误的文件名时,它将失败,但是在两种情况下, WEXITSTATUS(status)的返回值始终为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. 阅读手册页和Google时,建议我根据状态码获取正确的值。

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. 如果为execl()提供一个不存在的文件名作为第一个参数,它将失败。 If this happens the program leaves without returning any specifiy value. 如果发生这种情况,程序将退出而不返回任何指定值。 So the default of 0 is returned. 因此,将返回默认值0

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 您没有将文件名从argv传递给子进程

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. 这是一个xcode问题,可以从控制台运行正常。 I am a Java guy, doing some assignments in CPP. 我是Java专家,在CPP中做一些作业。 Nevertheless, it might come handy to someone getting stuck at similar issue. 但是,对于陷入类似问题的人来说可能会很方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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