【问题标题】:How to get the status of command run by system()如何获取 system() 运行的命令的状态
【发布时间】:2012-02-15 00:50:32
【问题描述】:

我在我的 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));
}

【问题讨论】:

    标签: c linux shell


    【解决方案1】:

    如果是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,删除了我自己的答案。请务必单独检查-1
    • 注意#include &lt;sys/wait.h&gt; 的需要。
    【解决方案2】:

    尝试使用WEXITSTATUS

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        当你阅读 opengroup 网站上的 man 时,它说:

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

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

        【讨论】:

          【解决方案5】:

          使用

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

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

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

          【讨论】:

          • 这里它将在终端上打印该命令的状态,但您不能在代码中包含该状态以供将来使用..
          猜你喜欢
          • 2016-03-18
          • 1970-01-01
          • 1970-01-01
          • 2012-09-23
          • 1970-01-01
          • 2012-05-29
          • 2020-01-16
          • 1970-01-01
          • 2010-09-06
          相关资源
          最近更新 更多