gpt4 book ai didi

c - 如何通过调用 exec 函数族的成员来获取程序运行的返回值?

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:01 26 4
gpt4 key购买 nike

我知道可以使用管道读取命令输出?但是如何获得返回值呢?例如我想执行:

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

如何获取 ping 命令的返回值以确定它返回的是 0 还是 1?

最佳答案

这是我很久以前写的一个例子。基本上,在您派生一个子进程并等待它的退出状态后,您可以使用两个宏检查状态。 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;
}

关于c - 如何通过调用 exec 函数族的成员来获取程序运行的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41104183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com