如何通过调用exec函数家族的成员来获得程序的返回值?

我知道可以读取pipe道输出命令吗? 但是获得回报值呢? 例如,我想执行:

execl("/bin/ping", "/bin/ping" , "-c", "1", "-t", "1", ip_addr, NULL); 

我怎么能得到返回值的ping命令,以找出它是否返回0或1?

这是我很久以前写的一个例子。 基本上,在分叉subprocess并wait其退出状态后,使用两个macros检查状态。 WIFEXITED用于检查进程是否正常退出, WEXITSTATUS检查返回的数字是否正常返回。

 #include <stdio.h> #include <unistd.h> #include <sys/wait.h> int main() { int number, statval; printf("%d: I'm the parent !\n", getpid()); if(fork() == 0) { number = 10; printf("PID %d: exiting with number %d\n", getpid(), number); exit(number) ; } else { printf("PID %d: waiting for child\n", getpid()); wait(&statval); if(WIFEXITED(statval)) printf("Child's exit code %d\n", WEXITSTATUS(statval)); else printf("Child did not terminate with exit\n"); } return 0; } 

你可以使用waitpid来获得你的subprocess的退出状态:

 int childExitStatus; waitpid( pID, &childExitStatus, 0); // where pID is the process ID of the child. 

exec函数familly不会返回,只有在启动时发生错误(如找不到文件到exec)时,返回int才会在这里。

在调用exec之前,必须从发送到分叉进程的信号中捕获返回值。

在你的信号处理程序中调用wait()或者waitpid() (你也可以在你的进程中调用wait()而不用任何信号处理程序。

无法理解和应用现有的答案。

在AraK的回答中 ,如果应用程序有多个subprocess在运行,则不可能知道哪个特定的subprocess产生了退出状态。 根据手册页,

wait()和waitpid()

wait()系统调用暂停调用进程的执行,直到它的一个子进程终止 。 呼叫等待(&状态)相当于:

  waitpid(-1, &status, 0); The **waitpid()** system call suspends execution of the calling process until a **child specified by pid** argument has changed state. 

因此,要获得特定subprocess的退出状态,我们应该将答案重写为:

 #include <stdio.h> #include <unistd.h> #include <sys/wait.h> int main() { int number, statval; int child_pid; printf("%d: I'm the parent !\n", getpid()); child_pid = fork(); if(child_pid == -1) { printf("could not fork! \n"); exit( 1 ); } else if(child_pid == 0) { execl("/bin/ping", "/bin/ping" , "-c", "1", "-t", "1", ip_addr, NULL); } else { printf("PID %d: waiting for child\n", getpid()); waitpid( child_pid, &statval, WUNTRACED #ifdef WCONTINUED /* Not all implementations support this */ | WCONTINUED #endif ); if(WIFEXITED(statval)) printf("Child's exit code %d\n", WEXITSTATUS(statval)); else printf("Child did not terminate with exit\n"); } return 0; } 

随意将这个答案转换成AraK答案的编辑。

您可以等待subprocess并获取其退出状态。 系统调用是等待(pid),尝试读取它。