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

Jee*_*tel 5 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);
}
Run Code Online (Sandbox Code Playgroud)

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

sh: ./test12.out: No such file or directory
0
system return is 32512
Run Code Online (Sandbox Code Playgroud)

这是我的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));
}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 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.
Run Code Online (Sandbox Code Playgroud)

  • +1,删除了我自己的答案.一定要单独检查"-1". (2认同)