0

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

3 回答 3

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. */
  }
  ...
于 2013-10-03T07:24:20.087 回答
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
于 2013-10-03T07:33:05.530 回答
-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.

于 2013-10-03T13:18:25.507 回答