Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run command and detect if it's successful by C language in Linux?

Tags:

c

linux

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;
}
like image 372
Suge Avatar asked Dec 09 '22 13:12

Suge


1 Answers

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

like image 74
Ingo Leonhardt Avatar answered Dec 11 '22 01:12

Ingo Leonhardt