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

我有这个c代码:

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

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

我的问题是:如何获得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 } } 

您必须在父进程中调用wait()waitpid() ,它将为您提供execl()执行的程序的退出状态。 不调用其中一个会使子进程在终止时仍然是僵尸,即一个已死但仍留在进程表中的进程,因为它的父进程对其返回代码不感兴趣。

 #include  #include  #include  ... 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()失败的必要条件。