如何通过调用exec函数族的成员来获取运行程序的返回值?
我知道可以用管道读取命令输出?但是如何获得回报值呢?例如,我想执行:如何通过调用exec函数族的成员来获取运行程序的返回值?,c,exec,C,Exec,我知道可以用管道读取命令输出?但是如何获得回报值呢?例如,我想执行: execl("/bin/ping", "/bin/ping" , "-c", "1", "-t", "1", ip_addr, NULL); 如何获取ping命令的返回值以确定它是否返回了0或1?exec函数通常不返回,只有在启动时出现错误(如未找到要执行的文件)时,才会返回int 在调用exec之前,必须从发送到分叉进程的信号中捕获返回值 在信号处理程序中调用wait或waitpid如果没有其他事情要做,您也可以在进程中调
execl("/bin/ping", "/bin/ping" , "-c", "1", "-t", "1", ip_addr, NULL);
如何获取ping命令的返回值以确定它是否返回了0或1?exec函数通常不返回,只有在启动时出现错误(如未找到要执行的文件)时,才会返回int 在调用exec之前,必须从发送到分叉进程的信号中捕获返回值
在信号处理程序中调用wait或waitpid如果没有其他事情要做,您也可以在进程中调用wait而不使用任何信号处理程序。您可以在子进程上等待并获取其退出状态。 系统调用为waitpid,请尝试了解它。您可以使用waitpid获取子进程的退出状态,如下所示:
int childExitStatus;
waitpid( pID, &childExitStatus, 0); // where pID is the process ID of the child.
这是我很久以前写的一个例子。基本上,在分叉子进程并等待其退出状态后,使用两个宏检查状态。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;
}
无法理解和应用现有答案 在中,如果应用程序有多个子进程正在运行,则不可能知道哪个特定子进程产生了退出状态。根据手册 等等 等待系统调用将暂停调用进程的执行,直到其一个子进程终止。呼叫等待状态(&S) 相当于:
waitpid(-1, &status, 0);
The **waitpid()** system call suspends execution of the calling process until a **child specified by pid** argument has changed state.
因此,为了获得特定子进程的退出状态,我们应该将答案改写为:
#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答案的编辑。您可以使用popen而不是exec系列。然后使用fgets或fscanf读取输出
感谢大家的有用和快速的回复;在WEXITSTATUSstatval中返回的值。如何检测ping命令的返回值?请编写exec,而不是exitnumber。但execl不返回任何值,如果失败,请执行execpt,因此ping命令返回0或1@Skuja正如我所说的,您将exec写在第一个块中。您将在第二个块中收到ping的状态,因为我们编写了wait&statval。不要忘记,在这种情况下,上面的程序将是ping的父程序。只是为了避免误解:waitpid返回的退出状态不是子程序返回的退出代码。详见阿拉克的答案。
char buff[MAX_BUFFER_SIZE];
FILE *pf = popen("your command", "r");
fscanf(pf, "%s", buff);
pclose(pf);