Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WaitForExit for a process on a remote computer

Tags:

c#

process

I'm using WMI to start a process on a remote machine. The call to create the process returns immediately and I also get the id of the process on the remote machine.

I would like to wait for the remote process to be completed. One option would be to poll whether a process on the remote machine with the given id still exists.

However, I was wondering whether there is a better way to achieve this, maybe using native WinAPI functions?

Just for additional information, this is the code that I am currently using to start the remote process:

ConnectionOptions connOptions = new ConnectionOptions();
connOptions.Impersonation = ImpersonationLevel.Impersonate;
connOptions.EnablePrivileges = true;

connOptions.Username = domainUserName;
connOptions.Password = password;

ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", host), connOptions);
manScope.Connect();

ObjectGetOptions objectGetOptions = new ObjectGetOptions();
ManagementPath managementPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass(manScope, managementPath, objectGetOptions);

ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
inParams["CommandLine"] = commandLine;

ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
like image 388
Dirk Vollmar Avatar asked Apr 14 '09 15:04

Dirk Vollmar


1 Answers

I don't know how effective this can be, you can use ManagementEventWatcher to watch a query.

Here is something I found on the net.

WqlEventQuery wQuery = 
 new WqlEventQuery("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process'");

using (ManagementEventWatcher wWatcher = new ManagementEventWatcher(scope, wQuery))
{    
  bool stopped = false;

  while (stopped == false)
  {
    using (ManagementBaseObject MBOobj = wWatcher.WaitForNextEvent())
    {
      if (((ManagementBaseObject)MBOobj["TargetInstance"])["ProcessID"].ToString() == ProcID)
      {
        // the process has stopped
        stopped = true;
      }
    }
  }

  wWatcher.Stop();
}
like image 109
Shay Erlichmen Avatar answered Oct 07 '22 03:10

Shay Erlichmen