2010-09-23 90 views
9

我有這樣的C代碼:我如何獲得由exec執行的程序的返回值?

if(fork()==0){ 
    execl("/usr/bin/fsck", "fsck", "/dev/c0d0p1s0", NULL); 
} 

它要求execl來檢查文件系統/dev/c0d0p1s0運行fsck

我的問題是:我怎樣才能得到fsck的返回值?

我需要返回值fsck來檢查文件系統是否一致。

謝謝。

回答

12

有父進程等待孩子退出:

pid_t pid = fork(); 
if (pid == -1) { 
    // error, no child created 
} 
else if (pid == 0) { 
    // child 
} 
else { 
    // parent 
    int status; 
    if (waitpid(pid, &status, 0) == -1) { 
    // handle error 
    } 
    else { 
    // child exit code in status 
    // use WIFEXITED, WEXITSTATUS, etc. on status 
    } 
} 
+0

是的,猜猜我誤解了!我試圖指出,返回代碼將在「errno」中設置。當然,閱讀該返回代碼父母必須等待孩子:) ...反正刪除了答案。 – KedarX 2010-09-23 10:05:05

+0

@Roger謝謝。我會嘗試一下,讓你知道結果是什麼。 – mnish 2010-09-23 10:20:51

+1

必須注意的是,在子節點中調用'execl()'的特殊情況下,你應該在這之後調用'_exit()'來防止子節點在execl()失敗的情況下繼續執行。你還應該在處理最終'execl()'失敗的父類中創建一個新案例。 – 2010-09-23 11:21:31

6

你必須調用父進程wait()waitpid(),它會給您execl()執行的程序的退出狀態。不調用其中一個會使子進程在終止時仍然是殭屍,即一個已經死了的進程,但因爲它的父進程對其返回代碼不感興趣而停留在進程表中。

#include <sys/types.h> 
#include <sys/wait.h> 
#include <unistd.h> 

... 

pid_t pid; 
int status; 

if ((pid = fork()) == 0) { 
    /* the child process */ 
    execl(..., NULL); 
    /* if execl() was successful, this won't be reached */ 
    _exit(127); 
} 

if (pid > 0) { 
    /* the parent process calls waitpid() on the child */ 
    if (waitpid(pid, &status, 0) > 0) { 
    if (WIFEXITED(status) && !WEXITSTATUS(status)) { 
     /* the program terminated normally and executed successfully */ 
    } else if (WIFEXITED(status) && WEXITSTATUS(status)) { 
     if (WEXITSTATUS(status) == 127) { 
     /* execl() failed */ 
     } else { 
     /* the program terminated normally, but returned a non-zero status */ 
     switch (WEXITSTATUS(status)) { 
      /* handle each particular return code that the program can return */ 
     } 
     } 
    } else { 
     /* the program didn't terminate normally */ 
    } 
    } else { 
    /* waitpid() failed */ 
    } 
} else { 
    /* failed to fork() */ 
} 

_exit()呼叫孩子,以防止它繼續執行的情況下,execl()失敗。其返回狀態(127)也有必要區分母公司最終的失敗情況execl()

相關問題