How to get the status of command run by system(

2019-05-01 01:33发布

问题:

I am using one system call in my c code

#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);
}

there isn't any test12.out file in my current folder. Now output is

sh: ./test12.out: No such file or directory
0
system return is 32512

Here is my shell command failed but how can I know that in my c code?

Edit:

So, can I do this

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));
}

回答1:

If a == -1, the call has failed. Otherwise, the exit code is WEXITSTATUS(a).

To quote 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:

Try using WEXITSTATUS:

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


回答3:

Check that a is not 0. Your 2nd line shows 0 because it's executed in different shell with no prior history, so that brand new shell reports "All is ok" to you.



回答4:

When you read the man in the opengroup website, it says :

If command is a null pointer, system() shall return non-zero to indicate that a command processor is available, or zero if none is available. [CX] The system() function shall always return non-zero when command is NULL.

[CX] If command is not a null pointer, system() shall return the termination status of the command language interpreter in the format specified by waitpid(). The termination status shall be as defined for the sh utility; otherwise, the termination status is unspecified. If some error prevents the command language interpreter from executing after the child process is created, the return value from system() shall be as if the command language interpreter had terminated using exit(127) or _exit(127). If a child process cannot be created, or if the termination status for the command language interpreter cannot be obtained, system() shall return -1 and set errno to indicate the error.



回答5:

Use

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

echo $? -- will provide you the exit status of command.

(Output of command can be avoided using redirection to /dev/null if you need only exit status)



标签: c linux shell