2011-01-18 2 views
1

스레드 내에서 타사 프로그램을 시작하고 C++로 stdout/stderr에서 결과를 얻으려고 기다려야합니다.C++로 스레드에서 응용 프로그램 시작

  • 어떤 방법을 사용할 수 있습니까?
  • 크로스 플랫폼입니까? 내 말은, 내가 cl/gcc 둘 다 사용할 수 있습니까?
+1

http://stackoverflow.com/questions/43116/how-can-i -run-an-external-program-from-c-and-parse-its-output은 같은 것을 말하는 것처럼 보입니다. – Nim

답변

1

: Windows에서

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

} 

:

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에서 수행하려면 특정 Windows createprocess을 사용해야 할 수도 있습니다.

이렇게 일반적으로 차단되므로 새 스레드에서 시작해야합니다. Windows에서 posix (pthreads)를 사용할 수 있지만 스레딩은 일반적으로 크로스 플랫폼이 아닙니다.

대안은 Qt 또는 wxWidgets 크로스 플랫폼 라이브러리와 같은 것을 사용하는 것입니다.

1

시스템은 플랫폼에 독립적이어야하지만 동일한 보안 권한을 사용하여 프로그램을 실행해야하는 경우 create process (win)/exec (others)를 사용하는 것이 좋습니다. 유닉스에

관련 문제