Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

wait until a program has finished

Status
Not open for further replies.

ceodav

Programmer
Feb 21, 2003
106
IT
Hi,
what's wrong in my function?
I want to wait until an exe has finished...

HINSTANCE id;

id = ShellExecute(NULL, NULL, EXE, c_Params, EXE_DIR, SW_SHOWNORMAL);


do
{
Sleep(100);

}while(OpenProcess(PROCESS_ALL_ACCESS, FALSE, (long)id)!=0);


thanks
D.
 
My approach is like this:


STARTUPINFO startupInfo;
PROCESS_INFORMATION processInformation;
ZeroMemory( &startupInfo, sizeof(startupInfo) );

BOOL started = CreateProcess
(
(LPCTSTR) 0,
(LPTSTR) "notepad hello.txt",
0,
0,
FALSE,
NORMAL_PRIORITY_CLASS,
(LPVOID)0,
(LPCTSTR)"G:\\Documents and Settings\\Administrator\\Desktop",
&startupInfo,
&processInformation
);
if(started)
{
while(GetProcessVersion(processInformation.dwProcessId))
{
Sleep(100);
}
MessageBox(0, "finished", "", 0);

Ion Filipski
1c.bmp
 
ceodav,

You ask : what's wrong ?

This is wrong : If ShellExecute succeeds, and the first OpenProcess succeeds, you have a handle to the process which you never close. That means the process-object will never be released from memory, not even when the process has finished. So the second call to OpenProcess will succeed too, even if the process has finished in the meantime. You create 10 handles every second. If you let it run long enough you will run out of system resources.

What you need to do is:
1. obtain a handle to the process only once. Do it your way or, if you used CreateProcess like Ion suggested, you can use processInformation.hProcess immediately after CreateProcess succeeded.
2. call WaitForSingleObject, using the handle from step 1.
3. DO NOT FORGET: Close the process-handle (and thread-handle processInformation.hThread if you used CreateProcess).



Marcel
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top