2012-01-20 55 views
2

看到我使用一个系统调用在我的C代码如何获得命令的系统运行()状态

#include <sys/stat.h> 
#include <stdio.h> 

int 
main(int argc, char *argv[]) 
{ 
    int a = system("./test12.out"); //here if i am giving any wrong commad 
    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 is 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)); 
} 

回答

15

如果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. 
+2

+1,删除了我自己的答案。一定要单独检查“-1”。 –

+0

现在看我的编辑...是否正确? –

3

尝试使用WEXITSTATUS

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

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

0

当你阅读的OpenGroup的网站的人,它说:

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

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

0

使用

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

echo $? - 将为您提供命令的退出状态。 (可以使用重定向到/ dev/null时避免命令的输出,如果你只需要退出状态)

+0

在这里它将在终端上打印该命令的状态,但不能在代码中使用该命令以备将来使用。 –