I've got a utility that outputs a list of files required by a game. How can I run that utility within a C program and grab its output so I can act on it within the same program?
UPDATE: Good call on the lack of information. The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux. Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout).
As I know, any address in a program only belongs itself, meaning that you can't invoke a function of another program thought its address. Data is code, code is data. As soon as your exploit payload (i.e. machine code) is read into memory by the process you're attacking, it has an address in the target process.
use "system" a in-built function. Say you want to invoke another C program with name abc.exe. system("abc.exe"); // provide absolute path if exe place at other directory.
As others have pointed out, popen()
is the most standard way. And since no answer provided an example using this method, here it goes:
#include <stdio.h> #define BUFSIZE 128 int parse_output(void) { char *cmd = "ls -l"; char buf[BUFSIZE]; FILE *fp; if ((fp = popen(cmd, "r")) == NULL) { printf("Error opening pipe!\n"); return -1; } while (fgets(buf, BUFSIZE, fp) != NULL) { // Do whatever you want here... printf("OUTPUT: %s", buf); } if (pclose(fp)) { printf("Command not found or exited with error status\n"); return -1; } return 0; }
Sample output:
OUTPUT: total 16 OUTPUT: -rwxr-xr-x 1 14077 14077 8832 Oct 19 04:32 a.out OUTPUT: -rw-r--r-- 1 14077 14077 1549 Oct 19 04:32 main.c
For simple problems in Unix-ish environments try popen()
.
From the man page:
The popen() function opens a process by creating a pipe, forking and invoking the shell.
If you use the read mode this is exactly what you asked for. I don't know if it is implemented in Windows.
For more complicated problems you want to look up inter-process communication.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With