gpt4 book ai didi

c# - WaitForExit 用于远程计算机上的进程

转载 作者:太空狗 更新时间:2023-10-29 23:04:46 25 4
gpt4 key购买 nike

我正在使用 WMI to start a process on a remote machine .创建进程的调用立即返回,我还获得了远程机器上进程的 ID。

我想等待远程进程完成。一种选择是轮询远程机器上具有给定 id 的进程是否仍然存在。

但是,我想知道是否有更好的方法来实现这一点,也许使用 native WinAPI 函数?

仅供引用,这是我当前用于启动远程进程的代码:

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);

最佳答案

不知道效果如何,可以用ManagementEventWatcher观看查询。

这是我在网上找到的。

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();
}

关于c# - WaitForExit 用于远程计算机上的进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/748239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com