开发者

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

This question already has answers here: 开发者_Python百科 Closed 12 years ago.

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


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);


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜