2011-09-13 37 views
1

嗨我創建了多個進程與CreateProcess ,我需要等待他們完成,分析結果。C,創建進程並等待

我不能WaitForSingleObject,因爲我需要所有的進程在同一時間運行。

由於每個進程在Process_Information(hProcess) 處有句柄,我可以使用WaitForMultipleObjects,但父進程沒有等待孩子結束。 可以使用WaitForMultipleObjects還是有更好的方法?

這是我正在創建的過程:

#define MAX_PROCESS 3 

STARTUPINFO si[MAX_PROCESS]; 
PROCESS_INFORMATION pi[MAX_PROCESS]; 
WIN32_FIND_DATA fileData; 
HANDLE find; 

int j=0, t=0; 

ZeroMemory(&si, sizeof(si)); 


for (t = 0; t < MAX_PROCESS; t++) 
    si[t].cb = sizeof(si[0]); 

ZeroMemory(&pi, sizeof(pi));  

while (FindNextFile(find, &fileData) != 0) 
{ 
    // Start the child process. 
    if (!CreateProcess(_T("C:\\Users\\Kumppler\\Documents\\Visual Studio 2010\\Projects\ \teste3\\Debug\\teste3.exe"), // No module name (use command line) 
         aux2,   // Command line 
         NULL,   // Process handle not inheritable 
         NULL,   // Thread handle not inheritable 
         TRUE,   // Set handle inheritance to FALSE 
         0,    // No creation flags 
         NULL,   // Use parent's environment block 
         NULL,   // Use parent's starting directory 
         &si[j],   // Pointer to STARTUPINFO structure 
         &pi[j])   // Pointer to PROCESS_INFORMATION structure 
     ) 
    { 
     printf("CreateProcess failed (%d).\n", GetLastError()); 
     return; 
    } 
    j++; 

    //find next file related 

}  
FindClose(find);   

WaitForMultipleObjects(MAX_PROCESS, &pi[j].hProcess, FALSE, INFINITE); 
//wait and analyze results 

順便說一句,我儘量不使用線程。

回答

2

如果您想等待所有的手柄將'bWaitAll'(第三個參數)設置爲'TRUE'。

3

WaitForMultipleObjects的預計句柄數組:

HANDLE hanldes[MAX_PROCESS]; 
for (int i = 0; i < MAX_PROCESS; ++i) 
{ 
    handles[i] = pi[i].hProcess; 
} 

WaitForMultipleObjects(MAX_PROCESS, handles, TRUE, INFINITE); 

你也應該知道,對於手柄的WaitForMultipleObjects的最大陣列大小被限制爲MAXIMUM_WAIT_OBJECTS(它是64)。

+0

謝謝,解決了這個問題 – Caio