开发者

How to capture process output in C?

开发者 https://www.devze.com 2023-01-27 15:03 出处:网络
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).

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消