I use the code below to run a command by C in Linux, I can get only the output of this function, how can I detect if it was run successfully? Are there any return codes representing this?
const char * run_command(const char * command)
{
const int BUFSIZE = 1000;
FILE *fp;
char buf[BUFSIZE];
if((fp = popen(command, "r")) == NULL)
perror("popen");
while((fgets(buf, BUFSIZE, fp)) != NULL)
printf("%s",buf);
pclose(fp);
return buf;
}
pclose()
returns the exit status of the program called (or -1 if wait4() failed(), see man page)
So you can check:
#include <sys/types.h>
#include <sys/wait.h>
....
int status, code;
status = pclose( fp );
if( status != -1 ) {
if( WIFEXITED(status) ) { // normal exit
code = WEXITSTATUS(status);
if( code != 0 ) {
// normally indicats an error
}
} else {
// abnormal termination, e.g. process terminated by signal
}
}
The macros I used are described here
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