How to capture process output in C?

Is there any analogue of the PHP system in C?

man systemsays it systemreturns the status of the command, but I need the output (as in PHP).

Of course, I can use pipes for this, but is there a standard way?

+3
source share
2 answers

You can use popen and a related function like:

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

Perfect link

+3
source

If you need the output of a command, you should use it popen()on Unix (with "r" to indicate what you want to read from the command).

FILE *fp = popen("some -convoluted command", "r");
...check for validity...
...read data from command...
pclose(fp);
+2
source

Source: https://habr.com/ru/post/1777900/


All Articles