C 如何获取system()运行的命令的状态

C 如何获取system()运行的命令的状态,c,linux,shell,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); } 这是我的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);
}
这是我的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.

尝试使用
WEXITSTATUS

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

检查a是否不是
0
。你的第二行显示了
0
,因为它是在不同的shell中执行的,没有以前的历史记录,所以全新的shell向你报告“一切正常”。

当你在opengroup网站上读到这个人时,它说:

若命令为空指针,system()应返回非零以指示命令处理器可用,若无可用,则返回零 可用。[CX]system()函数应始终返回非零 当命令为空时

[CX]如果命令不是空指针,system()将返回 命令语言解释器的终止状态,格式为 由waitpid()指定。终止状态应符合以下定义: sh实用程序;否则,终止状态未指定。如果 某些错误阻止命令语言解释器执行 创建子进程后,system()的返回值 应视为命令语言解释器已终止使用 出口(127)或_出口(127)。如果无法创建子进程,或者 命令语言解释器的终止状态不能为 获取后,system()将返回-1并设置errno以指示 错误

使用

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


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

+1,删除了我自己的答案。请确保分别检查
-1
。注意需要
#include
。此处它将在终端上打印该命令的状态,但您的代码中不能有该状态供将来使用。。
int a = WEXITSTATUS(system("./test12.out"));
system("your command; echo $?");