启动进程后获取友好名称 [英] Getting the friendly name for a Process after starting it
问题描述
我正在为嵌入式系统的看门狗服务编写代码,该服务监视一些专有进程并在必要时重新启动它们.(在您问之前,与恶意软件无关.这只是一项业务要求)
I'm coding a watchdog service for an embedded system that monitors some proprietary processes and restarts them if necessary. (Nothing to do with malware, before you ask. It's just a business requirement)
我需要从刚刚创建的进程中检索友好名称,以便以后可以使用该名称检索该进程以监视其运行状况.
I need to retrieve the friendly name from a process I have just created, so that later I can retrieve that process using that name in order to monitor its health.
我的问题如下:
-
如果我尝试在
Process.Start()
之后立即读取Process.ProcessName
,则会收到InvalidOperationException
,因为它流程尚未完全创建.
If I try to read
Process.ProcessName
right afterProcess.Start()
, I get anInvalidOperationException
because it the process has not been fully created yet.
如果我使用 Process.WaitForInputIdle()
,也会发生同样的情况,但是由于这需要消息泵,并且许多可执行文件可能是实际应用程序的无UI启动器,因此可能不是一个选项.
The same happens if I use Process.WaitForInputIdle()
, but since this requires a message pump and many executables could be UI-less launchers for the actual application, this might not be an option.
我需要在创建过程之后立即进行操作,然后再进行其他操作.
I need to get the friendly name right after creating the process, before doing anything else.
这是一个代码段:
var startInfo = new ProcessStartInfo { FileName = "notepad.exe" };
var process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForInputIdle();
var friendlyName = process.ProcessName;
例如,如果正在启动的进程是Firefox,则会在最后一行抛出 InvalidOperationException
.
This will throw an InvalidOperationException
on the last line if the process being started is Firefox, for example.
那我该怎么做?有没有更安全的方法?
So how would I do this? Is there a safer method?
添加了一个代码段以进行澄清.重新解释整个问题以便澄清,将无关紧要的内容排除在外.
Added a code snippet for clarification. Rephrased the whole question for clarification, left irrelevant stuff out.
推荐答案
好,因此,经过大量研究,我不得不求助于有些棘手的解决方案.
Ok, so after a lot of research I had to resort to a somewhat hacky solution.
根据 Process.GetProcessesByName()文档,"进程名称是该进程的友好名称,例如Outlook,不包含.exe扩展名或路径.".
考虑到这一点,我使用以下代码解决了该问题:
Considering this, I worked around the problem using this code:
var startInfo = new ProcessStartInfo { FileName = "notepad.exe" };
var process = new Process();
process.StartInfo = startInfo;
process.Start();
var friendlyName = Path.GetFileNameWithoutExtension(startInfo.FileName);
就像我说的那样,它仍然有点怪异,但至少完成了工作并让我继续前进.
As I said, it still feels kinda hacky, but at least it got the job done and allowed me to move on.
仍然感谢您的所有评论!
Thanks for all your comments anyway!
这篇关于启动进程后获取友好名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!