java中如何获取进程id?
我正在尝试找到一种以编程方式打开和关闭应用程序的方法。我可以轻松地使用启动应用程序
Runtime.getRuntime().exec(new String[] {"open", "<path to application>"});
,但是,我能找到关闭它的唯一方法是使用该行
Runtime.getRuntime().exec(new String[] {"kill", "<process id#>"});
,除了手动打开终端并使用 top 查找 # 之外,我无法找到获取 id # 的方法。如果有一种编程方式来获取此 ID,或者只是一种更好的方式来打开和关闭应用程序,我很想听听。
谢谢
I am trying to find a way to programmaticaly open and close an application. I can launch the application easily using
Runtime.getRuntime().exec(new String[] {"open", "<path to application>"});
however, the only way I can find to close it is to use the line
Runtime.getRuntime().exec(new String[] {"kill", "<process id#>"});
and I can't find anyway to get the id # other than manually opening terminal and using top to find the #. If there is a programmatic way to get this id, or just a better way to go about opening and closing applications i would love to hear about it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
java.lang.ProcessBuilder
启动子进程。返回的Process
对象有一个destroy()
方法,可以让你杀死它。Use a
java.lang.ProcessBuilder
to start the subprocess. The returnedProcess
object has adestroy()
method which will let you kill it.这可能与原始海报不再相关(由于经过的时间),但只是为了完整性......
您可以通过 exec(...) 获得进程对象的句柄 命令:
然后您可以随时使用
destroy()
进行终止:注意:这可能与 Jim 所描述的类似,但不使用
ProcessBuilder
。This probably isn't relevant anymore to the original poster (due to the elapsed time) but just for the sake of completeness...
You get a handle to the process object as a result of the
exec(...)
command:You can then kill at any later time with
destroy()
:Note: This might be similar to what Jim was describing but not using the
ProcessBuilder
.