Program Resource

Resource libraries for programmers and developers

If you want to call external process and want to wait for it to terminate, you can call CreateProcess function and wait using WaitForSingeObject API.

However, some process just launches child process and terminates immediately, resulting application still running but process terminates and returns to code.

Below is sample code you can use in such case, where it monitors for process and child processes, and wait for all family process to terminate.

BOOL RunandWait(char *runfname,DWORD *dwretval)
{
	//Run and track process and child process, wait for all family process to terminate
	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	DWORD i;
	HANDLE hProcess;
	BOOL bJobAllEnd;

	si.cb = sizeof(si);
	si.lpReserved = NULL;
	si.lpDesktop = NULL;
	si.lpTitle = NULL;
	si.dwFlags = 0;
	si.cbReserved2 = 0;
	si.lpReserved2 = NULL;

	if (!CreateProcess(NULL,runfname,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi))
		return FALSE;

	PJOBOBJECT_BASIC_PROCESS_ID_LIST pList;
	pList = (PJOBOBJECT_BASIC_PROCESS_ID_LIST)GlobalAlloc(GMEM_FIXED, 10000);

	HANDLE hJob;
	hJob = CreateJobObject(NULL, "Paging Job Object");

	AssignProcessToJobObject(hJob, pi.hProcess);

	do {
		QueryInformationJobObject(hJob, JobObjectBasicProcessIdList, pList, 10000, NULL);

		bJobAllEnd = TRUE;

		for(i=0; i<pList->NumberOfProcessIdsInList; i++)
		{
			hProcess = OpenProcess(SYNCHRONIZE, FALSE, pList->ProcessIdList[i]);
			if(hProcess != NULL)
			{
				CloseHandle(hProcess);
				bJobAllEnd = FALSE;
			}
		}

		Sleep(500);
	} while(!bJobAllEnd);

	GlobalFree(pList);
	CloseHandle(hJob);

	if (dwretval)
		GetExitCodeProcess(pi.hProcess, dwretval);

	return TRUE;
}

This post is also available in: Japanese

Leave a Reply

Your email address will not be published. Required fields are marked *


*