Search code examples
c++processlaunching-application

Launching an application from a thread with C++


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?

Solution

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