Process.start() 启动的进程返回错误的进程 ID? [英] Process started by Process.start() returns incorrect process ID?

查看:25
本文介绍了Process.start() 启动的进程返回错误的进程 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码启动一个可执行文件:

I am starting an executable using this code:

Process proc = new Process();
proc.StartInfo.FileName = executablePath;
proc.Start();
proc.WaitForInputIdle();

在调用 proc.Id 之后,它给了我一些整数,这不是真正的进程 ID.在任务管理器中,此进程有另一个 ID,而且我正在使用 MS UI 自动化来访问此应用程序,它也返回与任务管理器中相同的 ID.所以我的问题是如何获取已启动进程的真实进程 ID?

after this calling proc.Id it gives me some integer, which is not real process ID. In the task manager there is another ID for this process and also I am using MS UI Automation to access this application, which also returns the same ID as in task manager. So my question is how can I get the real process ID of started process?

更新

我发现在 Windows 7 上它工作正常并返回正确的 ID,但在 Windows XP 上则不行.可能是什么原因?

I found out that on Windows 7 it works fine and returns me the right ID, but not on Windows XP. What can be the reason?

场景

应用场景如下.我有一个正在运行的嵌入式 HTTP 服务器,它不是由我实现的,(here 是来源).客户端连接到 Web 服务器并发送运行程序的请求.在我的服务器的请求处理程序中,我只是使用 Process.start() 来启动请求的应用程序.作为 Web 服务器,该程序为连接到它的每个客户端会话创建线程(我认为是这样,因为我没有编写它).这是否有助于确定问题,因为它仅存在于 Windows XP X86 Service Pack 3 上?

The scenario of the application is the following. I have a running embedded HTTP server, which is implemented not by me, (here is the source). The client connects to the web server and sends a request to run a program. In the request handler of my server I am just using Process.start() to start the requested application. As a web server the program creates threads for every client session connected to it (I assume so, as I didn't wrote it). Can this somehow help to identify the problem as it exists only on Windows XP X86 Service Pack 3?

推荐答案

我是如何做到的一个例子:

An example of how I did it:

    bool started = false;
    var p = new Process();

    p.StartInfo.FileName = "notepad.exe";

    started = p.Start();

    try {
      var procId = p.Id;
      Console.WriteLine("ID: " + procId);
    }
    catch(InvalidOperationException)
    {
        started = false;
    }
    catch(Exception ex)
    {
        started = false;
    }

否则,尝试使用这样的句柄:
使用处理程序
获取处理程序

Otherwise, try using handles like this:
Using handlers
Getting handler

hWnd = (int) process.MainWindowHandle;
int processId;
GetWindowThreadProcessId(hWnd, out processId);

[DllImport("user32")]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId);

旁注:
如果您获取进程数组并对其进行迭代并比较 PID,会发生什么情况?

Side note:
What happens if you get the array of process and iterate over them and compare the PIDs?

Process[] p = Process.GetProcessesByName( "testprogram" );
foreach(var proc in p)
    Console.WriteLine("Found: "+proc.Id == myExpectedProcId);

这篇关于Process.start() 启动的进程返回错误的进程 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆