如何获得一个程序的返回值,通过呼叫的功能EXEC家族的一员跑了? [英] How to get the return value of a program ran via calling a member of the exec family of functions?

查看:118
本文介绍了如何获得一个程序的返回值,通过呼叫的功能EXEC家族的一员跑了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,它可以读取命令的输出与管道?但是,关于得到的返回值是什么?比如我要执行:

I know that it is possible to read commands output with a pipe? But what about getting return value ? For example i want to execute:

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

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

How can i get returned value of ping command to find out if it returned 0 or 1?

推荐答案

下面是我很久以前写的一个例子。基本上,后叉一个子进程,你退出状态,检查使用两个宏的状态。 WIFEXITED 用于检查过程中正常退出,而 WEXITSTATUS 检查返回的数字是它正常返回情况下什么

Here is an example I wrote long time ago. Basically, after you fork a child process and you wait its exit status, you check the status using two Macros. WIFEXITED is used to check if the process exited normally, and WEXITSTATUS checks what the returned number is in case it returned normally:

#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;
}

这篇关于如何获得一个程序的返回值,通过呼叫的功能EXEC家族的一员跑了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆