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));
}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With