Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to capture result from system() in C/C++ [duplicate]

Tags:

c++

c

sockets

Possible Duplicate:
How can I run an external program from C and parse its output?

Hi,

Could someone please tell us how to capture a result when executing system() function ?

Actually I wrote a c++ program that displays the machine's IP address, called "ipdisp" and I want when a sever program executes this ipdisp program, the server captes the display IP address. So, is this possible? if yes, how?

thanks for your replies

like image 865
make Avatar asked Feb 14 '10 04:02

make


2 Answers

Yes, you can do this but you can't use system(), you'll have to use popen() instead. Something like:

FILE *f = popen("ipdisp", "r");
while (!feof(f)) {
    // ... read lines from f using regular stdio functions
}
pclose(f);
like image 140
Greg Hewgill Avatar answered Sep 21 '22 12:09

Greg Hewgill


Greg is not entirely correct. You can use system, but it's a really bad idea. You can use system by writing the output of the command to a temporary file and then reading the file...but popen() is a much better approach. For example:

#include <stdlib.h>
#include <stdio.h>
void
die( char *msg ) {
    perror( msg );
    exit( EXIT_FAILURE );
}

int
main( void )
{
    size_t len;
    FILE *f;
    int c;
    char *buf;
    char *cmd = "echo foo";
    char *path = "/tmp/output"; /* Should really use mkstemp() */

    len = (size_t) snprintf( buf, 0,  "%s > %s", cmd, path ) + 1;
    buf = malloc( len );
    if( buf == NULL ) die( "malloc");
    snprintf( buf, len, "%s > %s", cmd, path );
    if( system( buf )) die( buf );
    f = fopen( path, "r" );
    if( f == NULL ) die( path );
    printf( "output of command: %s\n", buf );
    while(( c = getc( f )) != EOF )
        fputc( c, stdout );
    return EXIT_SUCCESS;
}

There are lots of problems with this approach...(portability of the syntax for redirection, leaving the file on the filesystem, security issues with other processes reading the temporary file, etc, etc.)

like image 1
2 revs Avatar answered Sep 22 '22 12:09

2 revs