WEXITSTATUS Example

From EggeWiki

Example of how to use WEXITSTATUS <geshi lang="c">

  1. include <iostream>


void run(const char * cmd) {

   printf("Executing command %s\n", cmd);
   int status = std::system(cmd);
   printf("raw status %d\n", status);
   if (status == -1) {
       printf("fork failed\n");
   } else if (WIFEXITED(status)) {
       printf("terminated with exit status %d\n",
                WEXITSTATUS(status));
   } else {
       printf("terminated abnormally\n");
       printf("You can't use WEXITSTATUS here, cause if you did you would get %d\n", WEXITSTATUS(status));
   }
   printf("\n");

}

int main(int argc, char *argv[]) {

   printf("argc: %d\n", argc);
   if (argc > 1) {
       printf("prepare to die!\n");
       return *(int*)(0);
   }
   run("/bin/true");
   run("/bin/false");
   run("/bin/maybe");
   run("./a.out Oh no");
   return 0;

} </geshi>

The output is:

argc: 1
Executing command /bin/true
raw status 0
terminated with exit status 0

Executing command /bin/false
raw status 256
terminated with exit status 1

Executing command /bin/maybe
sh: /bin/maybe: No such file or directory
raw status 32512
terminated with exit status 127

Executing command ./a.out Oh no
argc: 3
prepare to die!
raw status 139
terminated abnormally
You can't use WEXITSTATUS here, cause if you did you would get 0