我用这code启动一个可执行文件:
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服务器,这是我不落实,(这里是源)。客户端连接到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;
}
否则,请尝试使用这样的句柄: Using处理 Getting处理器
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);