Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the status of command run by system()

Tags:

c

linux

shell

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));
}
like image 960
Jeegar Patel Avatar asked Jan 20 '12 12:01

Jeegar Patel


People also ask

What is the command to get the exit status of the most recent command process?

To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.

What is exit status in Unix?

Exit status is an integer number. 0 exit status means the command was successful without any errors. A non-zero (1-255 values) exit status means command was a failure.

How do you execute a command in C++?

You can use the popen and pclose functions to pipe to and from processes. The popen() function opens a process by creating a pipe, forking, and invoking the shell. We can use a buffer to read the contents of stdout and keep appending it to a result string and return this string when the processes exit.


1 Answers

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.
like image 122
NPE Avatar answered Oct 05 '22 02:10

NPE