mni*_*ish 11 c exec return-value
我有这个c代码:
if(fork()==0){
execl("/usr/bin/fsck", "fsck", "/dev/c0d0p1s0", NULL);
}
Run Code Online (Sandbox Code Playgroud)
它调用execl运行fsck来检查文件系统/dev/c0d0p1s0.
我的问题是:我怎样才能获得返回值fsck?
我需要返回值fsck来检查文件系统是否一致.
谢谢.
小智 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
}
}
Run Code Online (Sandbox Code Playgroud)
您必须调用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() */
}
Run Code Online (Sandbox Code Playgroud)
_exit()孩子的呼叫是为了防止它在execl()失败的情况下继续执行.其返回状态(127)对于区分execl()父母最终失败的情况也是必要的.