Ubuntu Java:查找特定程序的 pid 并终止该程序
我正在尝试创建一个应用程序来检查此特定应用程序是否正在运行,然后在指定的时间后终止该应用程序。我打算获取应用程序的 pid。如何获取应用程序的 pid?
谢谢
I'm trying to make an application that checks if this specific application is running, then kill the app after a specified amount of time. I'm planning to get the pid of the app. How can I get the pid of the app?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以尝试 ps -aux | grep foobar 获取 pid,然后对其发出
kill
命令,或者您可能想要使用pkill
foobar
,在这两种情况下foobar
都是您想要的应用程序的名称终止。You might try
ps -aux | grep foobar
for getting the pid, then issuing thekill
command against it, alternatively you might want to usepkill
foobar
, in both casesfoobar
being the name of the app you want to terminate.java 进程的 pid -eg
ps -aux | java | grep | awk '{print $2}'
。您还可以调用
jps
,它会给您一个进程列表。这样做的缺点是它只会显示发出 jps 命令的用户的进程。pid's for java processes -e.g
ps -aux | grep java | awk '{print $2}'
.You can also call
jps
which will give you a process list. A drawback of this is that it will only show you processes for the user issuing the jps command.您可以使用
pidof
获取应用程序的 pidpidof
you can use
pidof
to get the pid of your applicationpidof <application name>
那这个怎么样?
How about this then?
如果您从脚本启动此应用程序,您可以使用特殊变量
$!
获取在后台创建的最后一个进程的 pid,您可以将该值保存在文件中以供以后使用你的关机功能。下面是一个例子:
If you're starting this application from script you can get the pid of the last process that was created in background by using the special variable
$!
, this value you can save on a file for later use on your shutdown function.Below is an example:
PS 辅助 | awk '/java/ {print "sleep 10; Kill "$2}' | Ubuntu 中的bash
中,
ps -aux
会抛出语法错误,而ps aux
则有效。输出通过管道传输到
awk
,它与 java 匹配行并休眠 10 秒,然后使用 pId 终止程序。注意要 bash 的管道。请随意指定您想要的时间长度,或者拨打您认为合适的其他电话。我注意到大多数其他答案都忽略了问题的“经过一定时间”的部分。您还可以通过调用 pidof java | 来完成此操作。 awk '{print "sleep 10; Kill "$1}' | bash 但选择权在你。我一般用ps aux。
ps aux | awk '/java/ {print "sleep 10; kill "$2}' | bash
in Ubuntu,
ps -aux
throws an syntax error, whereps aux
works.the output is piped to
awk
which matches lines with java and sleeps for 10seconds and then kills the program with the pId. notice the pipe to bash. Feel free to specify however long you want, or to call what ever other calls you feel appropriate. I notice most of the other answers neglected to catch the 'after a certain amount of time' part of the quesiton.you could also accomplish this by calling
pidof java | awk '{print "sleep 10; kill "$1}' | bash
but the choice is yours. I generally use ps aux.您可能必须使用 Runtime.exec 并抓取它们的输出。我认为 Java 程序无法轻松检查/访问它未创建的进程。
You'll probably have to invoke the
ps
andkill
Unix commands using Runtime.exec and scrape their output. I don't think a Java program can easily inspect / access processes it didn't create.查找Linux下java进程的pid
可以参考这个链接...它告诉你如何找到特定类名的pid
Find the pid of a java process under Linux
you can refer to this link...it tell you about finding a pid of specific class name