WEXITSTATUS始终返回0

时间:2013-10-03 07:15:27

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

我正在使用wc分配进程并运行execl命令。现在在正确的参数下,它运行正常,但是当我给出错误的文件名时,它会失败,但在这两种情况下返回值都是 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 {     
        }
    }
}

3 个答案:

答案 0 :(得分: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. */
  }
  ...

答案 1 :(得分: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

答案 2 :(得分:-1)

这是一个xcode问题,从控制台运行正常。我是一个Java人,在CPP做一些任务。然而,对于陷入类似问题的人来说,它可能会派上用场。

相关问题