6

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

Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
sam
  • 229
  • 5
  • 12

4 Answers4

8

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();
Chris Taylor
  • 52,623
  • 10
  • 78
  • 89
4

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);
Aoi Karasu
  • 3,730
  • 3
  • 37
  • 61
0

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);
}
jweyrich
  • 31,198
  • 5
  • 66
  • 97
0

CreateProcessAsUser returns you a structure PROCESS_INFORMATION, which contains hProcess - process handle. This is a valid handle for WaitForSingleObject/WaitForMultipleObjects functions.

MSDN: WaitForSingleObject, WaitForMultipleObjects

max
  • 33,369
  • 7
  • 73
  • 84