如何获取系统运行的命令状态()

前端之家收集整理的这篇文章主要介绍了如何获取系统运行的命令状态()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我在我的c代码中使用一个系统调用

#include dio.h>

int
main(int argc,char *argv[])
{
    int a = system("./test12.out");  //here if i give any wrong command
    system("echo $?")
    printf("system return is %d",a);
}

我当前文件夹中没有任何test12.out文件.现在输出

sh: ./test12.out: No such file or directory
0
system return is 32512

这是我的shell命令失败但我怎么知道我的c代码

编辑:

那么,我可以这样做吗?

int main(int argc,char *argv[])
{
    int a = system("dftg");

    if(a == -1)
        printf("some error has occured in that shell command");
    else if (WEXITSTATUS(a) == 127)
        printf("That shell command is not found");
    else
        printf("system call return succesfull with  %d",WEXITSTATUS(a));
}
最佳答案
如果a == -1,则呼叫失败.否则,退出代码为WEXITSTATUS(a).

引用man 3系统:

RETURN VALUE
       The value returned is -1 on  error  (e.g.   fork(2)  Failed),and  the
       return  status  of the command otherwise.  This latter return status is
       in the format specified in wait(2).  Thus,the exit code of the command
       will  be  WEXITSTATUS(status).   In case /bin/sh could not be executed,the exit status will be that of a command that does exit(127).

       If the value of command is NULL,system() returns non-zero if the shell
       is available,and zero if not.
原文链接:https://www.f2er.com/linux/440733.html

猜你在找的Linux相关文章