我如何获得由exec执行的程序的返回值?

我如何获得由exec执行的程序的返回值?

问题描述:

我有这样的C代码:我如何获得由exec执行的程序的返回值?

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

它要求execl来检查文件系统/dev/c0d0p1s0运行fsck

我的问题是:我怎样才能得到fsck的返回值?

我需要返回值fsck来检查文件系统是否一致。

谢谢。

有父进程等待孩子退出:

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

你必须调用父进程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()