Running shell commands from C/C++

Hi guys,

I know using system() we can run unix commands but the problem is, I can't get any returns with the system(). I am returning stuff from my shell scripts that I need to be able to read from my C code.

Anybody has cure to this problem? :))

Thanks

Hello,

I remember doing this some time ago,

If you want to capture the output, consider popen() if your C library supports it.

(v)fork(), exec() might be worth a look too

Sorry I couldn't be more help, I had a dig around for the old code (SDL Battery Status App) but I couldn't find it

Hello

popen function should do this. You can execute a command using popen function in either read or write mode and the result will be return as a file pointer. You can then read the result from the command using the file pointer as you normally do..

A simple example i got from googling is below
#include <stdio.h>

int main() {
FILE *in;
extern FILE *popen();
char buff[512];

/* popen creates a pipe so we can read the output
of the program we are invoking */
if (!(in = popen("netstat -n", "r"))) {
exit(1);
}

/* read the output of netstat, one line at a time */
while (fgets(buff, sizeof(buff), in) != NULL ) {
printf("Output: %s", buff);
}

/* close the pipe */
pclose(in);
}

Hope this should help you

Regards
Collins