2011-01-18 10 views
1

我需要在線程內啓動第三方程序,等待使用C++從stdout/stderr獲得結果。從C++的線程啓動應用程序

  • 有什麼方法可用?
  • 他們是跨平臺嗎?我的意思是,我可以將它們用於cl/gcc嗎?
+1

http://stackoverflow.com/questions/43116/how-can-i從c-and-parse-its-output運行外部程序看起來像是在談論同樣的事情...... – Nim

回答

1

在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(); 
    } 

} 

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

} 
1

有一組posix函數來啓動外部可執行文件 - 請參閱exec - 它們是跨平臺的。要在Windows上執行一些特定的任務,您可能需要使用特定的窗口createprocess

這些通常會阻止,因此您必須在新線程中啓動它們。線程通常不是跨平臺的,儘管你可以在windows上使用posix(pthreads)。

另一種方法是使用諸如Qt或wxWidgets跨平臺庫之類的東西。

1

系統應該是獨立的平臺,但如果擔心運行具有相同安全權限的程序,您可能希望堅持使用createprocess(win)/ exec(others)。

相關問題