How can I execute external commands in C++/Linux?

前端 未结 3 1269
无人共我
无人共我 2020-11-28 10:11

I just want to know which is the best way to execute an external command in C++ and how can I grab the output if there is any?

Edit: I Guess I had t

相关标签:
3条回答
  • 2020-11-28 10:26

    popen definitely does the job that you're looking for, but it has a few drawbacks:

    • It invokes a shell on the command you're executing (which means that you need to untaint any user provided command strings)
    • It only works in one direction, either you can provide input to the subprocess or you can read its output.

    If you want invoke a subprocess and provide input and capture output then you'll have to do something like this:

    int Input[2], Output[2];
    
    pipe( Input );
    pipe( Output );
    
    if( fork() )
    {
        // We're in the parent here.
        // Close the reading end of the input pipe.
        close( Input[ 0 ] );
        // Close the writing end of the output pipe
        close( Output[ 1 ] );
    
        // Here we can interact with the subprocess.  Write to the subprocesses stdin via Input[ 1 ], and read from the subprocesses stdout via Output[ 0 ].
        ...
    }
    else
    {    // We're in the child here.
         close( Input[ 1 ] );
         dup2( Input[ 0 ], STDIN_FILENO );
         close( Output[ 0 ] );
         dup2( Output[ 1 ], STDOUT_FILENO );
    
         execlp( "ls", "-la", NULL );
    }
    

    Of course, you can replace the execlp with any of the other exec functions as appropriate.

    0 讨论(0)
  • 2020-11-28 10:42

    Use the popen function.

    Example (not complete, production quality code, no error handling):

    FILE* file = popen("ls", "r");
    // use fscanf to read:
    char buffer[100];
    fscanf(file, "%100s", buffer);
    pclose(file);
    
    0 讨论(0)
  • 2020-11-28 10:44

    An example:

    #include <stdio.h>
    
    int main() {
        FILE * f = popen( "ls -al", "r" );
        if ( f == 0 ) {
            fprintf( stderr, "Could not execute\n" );
            return 1;
        }
        const int BUFSIZE = 1000;
        char buf[ BUFSIZE ];
        while( fgets( buf, BUFSIZE,  f ) ) {
            fprintf( stdout, "%s", buf  );
        }
        pclose( f );
    }
    
    0 讨论(0)
提交回复
热议问题