如何获取exec执行的程序的返回值?

时间:2010-09-23 09:11:04

标签: c exec return-value

我有这个c代码:

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

它调用execl来运行fsck以检查文件系统/dev/c0d0p1s0

我的问题是:如何获得fsck的返回值?

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

谢谢。

2 个答案:

答案 0 :(得分:13)

让父进程等待子进程退出:

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
  }
}

答案 1 :(得分: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()失败的情况。