开发者

Launching an application from a thread with C++

I need to launch a 3rd party program inside a thread, wait to get the re开发者_运维百科sults both from stdout/stderr with C++.

  • What methods are available?
  • Are they cross-platform? I mean, can I use them both for cl/gcc?


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

}


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜