manatails008
manatails008

Reputation: 229

C run external program and get the result

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

if there is an executable called dummy, and it displays 4 digit number in command prompt when executed, I want to know how to run that executable and get the 4 digit number that it had generated. In C.

Upvotes: 4

Views: 3209

Answers (4)

Sam
Sam

Reputation: 278

popen() handles this quite nicely. For instance 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, hopefully it's helpful. Make sure to include stdio in order to use this.

Upvotes: 4

paxdiablo
paxdiablo

Reputation: 881113

This is not actually something ISO C can do on its own (by that I mean the standard itself doesn't provide this capability) - possibly the most portable solution is to simply run the program, redirecting its standard output to a file, like:

system ("myprog >myprog.out");

then use the standard ISO C fopen/fread/fclose to read that output into a variable.

This is not necessarily the best solution since that may depend on the underlying environment (and even the ability to redirect output is platform-specific) but I thought I'd add it for completeness.

Upvotes: 4

Ryan Calhoun
Ryan Calhoun

Reputation: 2363

There is popen() on unix as mentioned before, which gives you a FILE* to read from.

Alternatively on unix, you can use a combination of pipe(), fork(), exec(), select(), and read(), and wait() to accomplish the task in a more generalized/flexible way.

The popen library call invokes fork and pipe under the hood to do its work. Using it, you're limited to simply reading whatever the process dumps to stdout (which you could use the underlying shell to redirect). Using the lower-level functions you can do pretty much whatever you want, including reading stderr and writing stdin.

On windows, see calls like CreatePipe() and CreateProcess(), with the IO members of STARTUPINFO set to your pipes. You can get a file descriptor to do read()'s using _open_ofshandle() with the process handle. Depending on the app, you may need to read multi-threaded, or it may be okay to block.

Upvotes: 3

Nicolas Viennot
Nicolas Viennot

Reputation: 3969

You can use popen() on UNIX.

Upvotes: 4

Related Questions