Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait for process to exit when using CreateProcessAsUser

Tags:

c#

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

like image 453
sam Avatar asked Jun 05 '10 12:06

sam


2 Answers

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();
like image 167
Chris Taylor Avatar answered Nov 15 '22 10:11

Chris Taylor


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);
like image 42
Aoi Karasu Avatar answered Nov 15 '22 10:11

Aoi Karasu