wait for process to exit when using CreateProcessAsUser
i'm using CreateProcessAsUser in c# to l开发者_开发百科aunch a process by a service my service needs to waiting for the process to exit but i don't know how i can do it, i don't want to use checking the process existion in processes list
The PROCESS_INFORMATION returns the handle to the newly created process (hProcess
), you can wait on this handle which will become signaled when the process exits.
You can use SafeWaitHandle encapsulate the handle and then use WaitHandle.WaitOne to wait for the process to exit.
Here is how you would wrap the process handle
class ProcessWaitHandle : WaitHandle
{
public ProcessWaitHandle(IntPtr processHandle)
{
this.SafeWaitHandle = new SafeWaitHandle(processHandle, false);
}
}
And then the following code can wait on the handle
ProcessWaitHandle waitable = new ProcessWaitHandle(pi.hProcess);
waitable.WaitOne();
Check out http://www.pinvoke.net/ for signatures. Here's a sime example.
const UInt32 INFINITE = 0xFFFFFFFF;
// Declare variables
PROCESS_INFORMATION pi;
STARTUPINFO si;
System.IntPtr hToken;
// Create structs
SECURITY_ATTRIBUTES saThreadAttributes = new SECURITY_ATTRIBUTES();
// Now create the process as the user
if (!CreateProcessAsUser(hToken, String.Empty, commandLine,
null, saThreadAttributes, false, 0, IntPtr.Zero, 0, si, pi))
{
// Throw exception
throw new Exception("Failed to CreateProcessAsUser");
}
WaitForSingleObject(pi.hProcess, (int)INFINITE);
CreateProcessAsUser
returns you a structure PROCESS_INFORMATION
, which contains hProcess
- process handle. This is a valid handle for WaitForSingleObject
/WaitForMultipleObjects
functions.
MSDN: WaitForSingleObject, WaitForMultipleObjects
You could use GetExitCodeProcess, but note that this function returns immediately.
Another approach is using WaitForSingleObject. But this requires the process to be opened with the SYNCHRONIZE flag. Example:
IntPtr hwnd = OpenProcess(SYNCHRONIZE, 0, pid);
if (hwnd != IntPtr.Zero) {
WaitForSingleObject(hwnd, INFINITE);
CloseHandle(hwnd);
}
精彩评论