3

I need to launch a 3rd party program inside a thread, wait to get the results both from stdout/stderr with C++.

  • What methods are available?
  • Are they cross-platform? I mean, can I use them both for cl/gcc?
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • 1
    http://stackoverflow.com/questions/43116/how-can-i-run-an-external-program-from-c-and-parse-its-output seems like it's talking about the same thing... – Nim Jan 18 '11 at 14:37

3 Answers3

2

On Unix:

http://linux.die.net/man/3/execl

#include <sys/types.h>
#include <unistd.h>

void run_process (const char* path){
    pid_t child_pid;

    /* Duplicate this process.  */
    child_pid = fork ();

    if (child_pid != 0){
        /* This is the parent process.  */

        int ret = waitpid(child_pid, NULL, 0);

        if (ret == -1){
            printf ("an error occurred in waitpid\n");
            abort ();
        }
    }
    else {
        execl (path, path);
        /* The execvp function returns only if an error occurs.  */
        printf ("an error occurred in execl\n");
        abort ();
    }

}

On Windows:

http://msdn.microsoft.com/en-us/library/ms682425%28v=vs.85%29.aspx

# include <windows.h>

void run_process (const char* path){
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    bool ret = = CreateProcess(
            NULL,          // No module name (use command line)
            path,          // Command line
            NULL,          // Process handle not inheritable
            NULL,          // Thread handle not inheritable
            false,         // Set handle inheritance to FALSE
            0,             // No creation flags
            NULL,          // Use parent's environment block
            NULL,          // Use parent's starting directory 
            &si,           // Pointer to STARTUPINFO structure
            &pi            // Pointer to PROCESS_INFORMATION structure
        )

    if (!ret){
        printf("Error");
        abort();
    }

    WaitForSingleObject(pi.hProcess, INFINITE);

    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

}
Squall
  • 4,344
  • 7
  • 37
  • 46
1

There is a set of posix functions to launch an external executable - see exec - which are cross platform. To do some specific tasks on windows you may need to use windows specific createprocess.

These generally block so you would have to start them in a new thread. Threading is generally not cross platform, although you can use posix (pthreads) on windows.

An alternative is to use somthing like Qt or wxWidgets cross platform libraries.

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
1

system should be platform independant, but you might want to stick with createprocess (win)/ exec (others) if there is a concern about running the program with the same security privledges.

Dan
  • 354
  • 1
  • 4