簡體   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