Reputation: 2897
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;
}
Upvotes: 4
Views: 1951
Reputation: 9904
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
Upvotes: 8
Reputation: 225042
From the pclose(3)
documentation:
The
pclose()
function waits for the associated process to terminate; it returns the exit status of the command, as returned bywait4(2)
.
Upvotes: 4