C run an external program and get the result

In C, how should I execute an external program and get its results, as if it were running in the console?

if there is an executable file called dummy and it displays a 4-digit number on the command line at runtime, I want to know how to run this executable and get the 4-digit number that it generated. In C.

+3
source share
4 answers

popen () handles this pretty well. For example, if you want to call something and read the results line by line:

char buffer[140];
FILE *in;
extern FILE *popen();
if(! (in = popen(somecommand, "r"""))){
    exit(1);
 }

 while(fgets(buff, sizeof(buff), in) != NULL){
      //buff is now the output of your command, line by line, do with it what you will
 }
 pclose(in);

This has worked for me before, hope it will be useful. Remember to enable stdio to use this.

+3
source

You can use popen()on UNIX.

+4

, ISO C ( , ) - , , , :

system ("myprog >myprog.out");

ISO C fopen/fread/fclose, .

, ( ), , .

+3

unix popen(), , FILE* .

unix pipe(), fork(), exec(), select() read() wait() / .

popen fork pipe . , stdout ( ). , , , stderr stdin.

In the windows, see type calls CreatePipe()and CreateProcess(), in doing so, the IO members STARTUPINFOare set into your channels. You can get a file descriptor to do read()with the help of a _open_ofshandle()process descriptor. Depending on the application, you may need to read multithreading, or it might be normal to block.

+2
source

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


All Articles