【问题标题】:WEXITSTATUS always returns 0WEXITSTATUS 总是返回 0
【发布时间】:2013-10-09 18:55:42
【问题描述】:

我正在分叉一个进程并使用execl 运行wc 命令。现在在正确的参数下,它运行良好,但是当我给出错误的文件名时,它会失败,但在这两种情况下,返回值 WEXITSTATUS(status) 始终为 0。

我认为我正在做的事情有问题,但我不确定是什么。阅读手册页和谷歌建议我应该根据状态代码获得正确的值。

这是我的代码:

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

【问题讨论】:

  • #include &lt;sys/wait.h&gt;了吗?
  • @KerrekSB:除非&lt;iostream&gt; 包含&lt;sys/wait.h&gt;(或&lt;unistd.h&gt; 包含),否则如果不包含&lt;sys/wait.h&gt;,代码将无法编译。 (话虽如此,它在 Mac OS X 10.8.5 和 GCC 4.8.1 上编译正常,没有明确的&lt;sys/wait.h&gt;,这让我很惊讶!)printf()cout 的混合很奇怪,容我们说。它是 C++——只是。但只是而已。 printf() 消息应以换行符结尾。当我运行代码时,我得到:wc: /Users/gabbi/learning/test/xyz.st: open: No such file or directoryChild terminated normallyexit status is 1 — 根据需要。
  • ...当我输入错误的文件名时...”请说明您指的是哪个文件名。
  • 澄清一下,这一切都是 Xcode 的问题。当我从控制台运行相同的代码时,它没有任何问题。

标签: c++ c operating-system fork wait


【解决方案1】:

如果你向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. */
  }
  ...

【讨论】:

    【解决方案2】:

    您没有将文件名从 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
    

    【讨论】:

      【解决方案3】:

      这是一个 xcode 问题,从控制台运行可以正常工作。我是一名 Java 人,在 CPP 中做一些作业。不过,对于陷入类似问题的人来说,它可能会派上用场。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-16
        • 1970-01-01
        • 2015-09-27
        • 2014-03-20
        • 2013-04-13
        • 2013-03-30
        • 2016-07-13
        • 2023-04-09
        相关资源
        最近更新 更多