Hi,
In my c program, i call the system("pgrep -c thttpd");
the return value is
//-- 0 - One or more processes matched the criteria.
//-- 1 - No process matched the criteria
but the output on the screen is 2.
how can i capture this output?
Thanks in advance
Alex
Hi!
You called system("...") in your C program. First of all, the returned value has to do with the exit status of the program run under system, not the output of the command!
Second: Every process (process is a running program) has it's standard output to send the output and a standard error to send error messages. In your case the messages possibly are error messages of "pgrep" process and are sent to your terminal (the default standard error chanel). To check thsi fact run your program as:
your_program >panos1 2>panos2
where your_program is the name of the executable, panos1 is a file to use as standard output and panos2 is a file to use as standard error. After running the above command, you probably have the messages in panos2 as this file is used as standard error for your executable and inherited to child processes too (e.g. pgrep run under system as a chile process).
Third: To capture the standard output (or the the standard error) of a process run as child of another process you have to use the pipe system calls or functions; see the manual pages in popen, pipe etc. It's not easy and some experience in the C language is needed.
Bye...
Just call popen() - it does the piping for you.
#include <stdio.h>
int main()
{
FILE *cmd=popen(("pgrep -c thttpd", "r");
char result[24]={0x0};
while (fgets(result, sizeof(result), cmd) !=NULL)
printf("%s\n", result);
pclose(cmd);
return 0;
}