i'm using CreateProcessAsUser in c# to launch 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With