Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return code of system()

Tags:

c

unix

system

ps

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main() {

int res = system("ps ax -o pid -o command | grep sudoku | grep gnome > /dev/null");

printf("res = %d \n", res);

return 0;
}

I want to see if sudoku is running or not by just examining the return code of system() (or any other call for that matter). I do not want any output to be printed anywhere.

I do not quite understand the return code of system() even after looking at the man page

Whether sudoku is running or not, I get res = 0.

like image 933
hari Avatar asked Aug 01 '11 21:08

hari


1 Answers

First of all, you should be using WEXITSTATUS(res). The standard clearly states:

If command is not a null pointer, system() shall return the termination status of the command language interpreter in the format specified by waitpid().

I suspect the problem is that the command actually succeeds (grep finds itself). Try not to redirect the output for a moment:

[cnicutar@fresh ~]$ ./test
  989 sh -c ps ax -o pid -o command | grep sudoku | grep gnome
res = 0

So, since every commands executes successfully, the return code will be 0 :-). You might have better luck with pgrep and the like.

like image 163
cnicutar Avatar answered Sep 28 '22 03:09

cnicutar