繁体   English   中英

WEXITSTATUS始终返回0

[英]WEXITSTATUS always returns 0

我正在分叉进程并使用execl运行wc命令。 现在,在正确的参数下,它可以正常运行,但是当我输入错误的文件名时,它将失败,但是在两种情况下, WEXITSTATUS(status)的返回值始终为0。

我认为自己的工作有问题,但是我不确定这是什么。 阅读手册页和Google时,建议我根据状态码获取正确的值。

这是我的代码:

#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 {     
        }
    }
}

如果为execl()提供一个不存在的文件名作为第一个参数,它将失败。 如果发生这种情况,程序将退出而不返回任何指定值。 因此,将返回默认值0

您可以像这样修复示例:

#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. */
  }
  ...

您没有将文件名从argv传递给子进程

代替

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

尝试这个,

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

我在机器上得到的输出

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

这是一个xcode问题,可以从控制台运行正常。 我是Java专家,在CPP中做一些作业。 但是,对于陷入类似问题的人来说可能会很方便。

暂无
暂无

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

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