WaitForSingleObject returns when process is not terminated

Hi,

I've been doing researches on the Internet about this problem for a couple of days now, but everything I tried seems to fail.

My C++ application is creating a process, using CreateProcess, to launch an application, while the main process waits for the completion of that application. This seems to work for Notepad.exe, but fails for MSWord or OpenOffice Writer.

The following is the code:

=============================
char rgvalue[MAX_PATH];
// Maybe AssocQueryString is better?
int rValue = (int) FindExecutable(split->tmpfile.c_str(), NULL, rgvalue);

if (rValue == (int) SE_ERR_OOM) printf("System out of memory/resources\n");
else if (rValue == (int) SE_ERR_FNF) printf("File not found\n");
else if (rValue == (int) SE_ERR_NOASSOC) printf("No associated executable\n");
else printf("%s\n", rgvalue);


STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

string cmdline
= "\"" + string(rgvalue) + "\" \"" + string(split->tmpfile.c_str()) + "\"";
char cmd[MAX_PATH];
strncpy(cmd, cmdline.c_str(), MAX_PATH-1);
cmd[MAX_PATH-1] = '\0';

HANDLE hJob = CreateJobObject(NULL, "Test");

if (!hJob) {
printf("CreateJobObject failed (%d).\n", GetLastError());
return -1;
}

if (!CreateProcess(NULL,
cmd,
NULL,
NULL,
FALSE,
CREATE_SUSPENDED,
NULL,
NULL,
&si,
&pi ) ) {
printf("CreateProcess failed (%d).\n", GetLastError());
return -2;
}

if (AssignProcessToJobObject(hJob, pi.hProcess) == 0) {
printf("AssignProcessToJobObject failed (%d).\n", GetLastError());
return -3;
}

ResumeThread(pi.hThread);

/*
JOBOBJECT_BASIC_PROCESS_ID_LIST pidList = {0};

while (1) {
if (!QueryInformationJobObject(hJob, JobObjectBasicProcessIdList,
&pidList, sizeof(pidList), NULL)) {
printf("AssignProcessToJobObject failed (%d).\n", GetLastError());
return -4;
}

printf("number of processes is %d\n", pidList.NumberOfAssignedProcesses);
Sleep(5000);
}
*/
printf("%X\n", WaitForSingleObject(pi.hProcess, INFINITE));

CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
CloseHandle(hJob);

========================

I did this with a JobOject, and waited on hJob. The prcoess hangs indefinitely in that case. I also tested without JobObject, and the behavior is the same as if I waited on the hProcess handle.

I used QueryInformationJobObject to debug the number of processes in the job, initially it was 1, then it became 0 after the application is launched, but before it ended.

I have a feeling that the child process is creating additional processes, and terminating the main process. This caused my waiting process to think that the child has ended.

I would like to know how I can wait for the real application to finish. And also, why creating notepad.exe works, but swriter.exe does not.

Thanks.
Last edited on
Topic archived. No new replies allowed.