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

标签 c exec

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

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/27599062/

相关文章:

javascript - Node.js:为 exec() 清理不受信任的用户输入

PHP exec() 和 SSL

php - 将 .mov 转换为 .mp4 php 的问题

c - 添加一个元素到链表的末尾

在非 IEEE 浮点实现中更改尾数的宽度

这个 memcpy 会导致未定义的行为吗?

c - 找出 valgrind 提出的问题

C 指针 - 非常基本的

c - Ubuntu C代码如何在另一个文件夹中执行命令

java - 在 C++ 或 Java 中以响应模式使用 cmd