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

时间:2012-01-20 12:46:23

标签: c linux shell

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

#include <sys/stat.h>
#include <stdio.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));
}

5 个答案:

答案 0 :(得分:21)

如果a == -1,则通话失败。否则,退出代码为WEXITSTATUS(a)

引用man 3 system

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.

答案 1 :(得分:3)

尝试使用WEXITSTATUS

int a = WEXITSTATUS(system("./test12.out"));

答案 2 :(得分:1)

检查a是否不是0。你的第二行显示0因为它在不同的shell中执行而没有先前的历史记录,因此全新的shell会向你报告“All is ok”。

答案 3 :(得分:0)

当你读到opengroup网站上的男人时,它说:

  
    

如果command是空指针,则system()将返回非零值以指示命令处理器可用,如果没有则返回零     可用。 [CX] system()函数应始终返回非零值     当命令为NULL时。

  
     

[CX]如果命令不是空指针,则system()应返回   格式中命令语言解释器的终止状态   由waitpid()指定。终止状态应如所定义   sh实用程序;否则,未指定终止状态。如果   某些错误会阻止命令语言解释程序执行   创建子进程后,从system()返回值   应该像命令语言翻译一样终止使用   退出(127)或_exit(127)。如果无法创建子进程,或者如果   命令语言解释器的终止状态不能   获得,system()应返回-1并设置errno以指示   错误。

答案 4 :(得分:0)

使用

system("your command; echo $?");

echo $? - 将为您提供命令的退出状态。

(如果只需要退出状态,可以使用重定向到/ dev / null来避免输出命令)

相关问题