我正在编写一个启动外部应用程序然后等待它和所有子进程退出的应用程序。
private int RunCmdAndGetExitCode(string command, string args, ProcessWindowStyle windowStyle, WaitEnum wait)
{
Process scriptProc = new Process();
scriptProc.StartInfo.FileName = command;
scriptProc.StartInfo.Arguments = args;
scriptProc.StartInfo.WindowStyle = windowStyle;
if (scriptProc.Start())
{
if (wait == WaitEnum.MainProcess)
{
scriptProc.WaitForExit();
return scriptProc.ExitCode;
}
else if(wait == WaitEnum.None)
{
return 0;
}
else if (wait == WaitEnum.ChildProcesses)
{
ProcessMonitorThread _procmon = new ProcessMonitorThread(this, scriptProc);
while (ThreadCount != 0)
{
Thread.Sleep(500);
}
return 0;
}
}
return -1;
}
ProcessMonitorThread
是一个继承自的类BackgroundWorker
public class ProcessMonitorThread : BackgroundWorker
{
private IChildCounter _Counter;
private Process _processToMonitor;
public ProcessMonitorThread(IChildCounter counter, Process processToMonitor)
{
_Counter = counter;
_Counter.ThreadCount++;
_processToMonitor = processToMonitor;
this.DoWork += new DoWorkEventHandler(ProcessMonitorThread_DoWork);
this.RunWorkerCompleted += new RunWorkerCompletedEventHandler(ProcessMonitorThread_RunWorkerCompleted);
this.RunWorkerAsync();
}
void ProcessMonitorThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_Counter.ThreadCount--;
}
void ProcessMonitorThread_DoWork(object sender, DoWorkEventArgs e)
{
int processid = _processToMonitor.Id;
_processToMonitor.WaitForExit();
foreach (int _childid in GetChildProcessIDs(processid))
{
Process ps = Process.GetProcessById(_childid);
new ProcessMonitorThread(_Counter, ps);
}
}
List<Int32> GetChildProcessIDs(int ProcessID)
{
List<Int32> _ChildProcesses = new List<Int32>();
// Use the ObjectQuery to get the list of configured printers
System.Management.ObjectQuery oquery =
new System.Management.ObjectQuery("SELECT * FROM Win32_Process WHERE ParentProcessId =" + ProcessID);
System.Management.ManagementObjectSearcher mosearcher =
new System.Management.ManagementObjectSearcher(oquery);
System.Management.ManagementObjectCollection _AllChildProcesses = mosearcher.Get();
foreach (ManagementObject _cprocess in _AllChildProcesses)
{
Int32 _processid;
_processid = Convert.ToInt32(_cprocess["ProcessId"]);
_ChildProcesses.Add(_processid);
}
return _ChildProcesses;
}
}
当我启动一个可以打印的应用程序时,它会启动 splwow64 并且该进程成为子进程之一。问题是当我关闭应用程序时,我启动了 splwow64 并没有关闭它,而是等待某种超时。只有当 splwow64 终止时,我的应用程序才会报告我启动的应用程序及其所有子进程都已终止。哪个是对的。但是我真的不想等待 splwow64。
有什么方法可以识别系统进程或在我的进程终止后可以继续运行的进程?
我知道我可以忽略名称为 splwow64 的进程,但这对我来说似乎有点解决方法。