运行进程并在Windows 7中获取其ID

时间:2011-11-06 22:21:35

标签: java windows linux shell process

在我的java项目中,我需要运行VLC Media Player(用于漫游),并根据要求我想停止流式传输。 在Linux中,我创建了以下bash脚本,它使用一些参数运行VLC进程,然后将其ID输出到标准输出:

cvlc $@ &
echo $!

然后我有以下java代码运行脚本并从stdin中读取它的ID:

Process proc = Runtime.getRuntime().exec("/path/to/script");
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
if(line!=null) {
    lastPID = new Integer(line);
    System.out.println("Last vlc PID=" + lastPID);
}

当我想停止流式传输时,我将使用相应的ID杀死进程:

Runtime.getRuntime().exec("kill " + lastPID);

有没有办法在Windows 7(cmd.exe或Windows PowerShell)中编写等效脚本?或者,有没有办法编写运行进程的纯(独立于平台的)java代码,然后获取它的ID并停止它?

2 个答案:

答案 0 :(得分:1)

有办法。但是为什么不尝试使用纯Java API终止进程?用户process.destroy()。它与kill PID完全相同。

要获取进程ID,您可以使用WMI。查看以下资源:http://blogs.technet.com/b/heyscriptingguy/archive/2006/06/01/how-can-i-find-the-process-id-associated-with-a-batch-file.aspx

您可以使用作为附加参数传递的某种标识符来运行您的进程,然后执行WMI select from Win32_Process where ...并将标准放入where子句中。但同样,你实际上并不需要这个。

答案 1 :(得分:0)

使用此方法:How to get the PID of running application in Windows?

然后使用PID调用它:

Runtime.getRuntime().exec("taskkill /F /PID " + PID_To_Be_Killed);