How to capture process output in C?
Is there any analog of PHP's system in C?
man system
says, that system
return status of the command, but I need the output (like in PHP).
Of course, I can use pipes for this, but is there any stan开发者_StackOverflow社区dard way?
You can make use of popen and related function as:
// command to be run.
char *cmd = "date";
// open pipe stream.
FILE *fp = popen(cmd,"r");
int ch;
// error checking.
if(!fp) {
fprintf(stderr,"Error popen with %s\n",cmd);
exit(1);
}
// read from the process and print.
while((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
// close the stream.
pclose(fp);
Ideone link
If you need the output of the command, you'd use popen()
on Unix (with "r" to indicate that you want to read from the command).
FILE *fp = popen("some -convoluted command", "r");
...check for validity...
...read data from command...
pclose(fp);
精彩评论