[英]Scala check if external process id (pid) is currently running?
I need to check if a specified process is currently running using Scala. 我需要检查当前是否正在使用Scala运行指定的进程。
All I have is the PID. 我只有PID。
Does Scala have an internal function or do I need to parse it using ps
? Scala有内部函数还是需要使用
ps
解析它?
Thank you. 谢谢。
You can import sys.process._
你可以导入
sys.process._
import sys.process._
scala> import sys.process._
import sys.process._
scala> "ps" !
PID TTY TIME CMD
570 ttys000 0:00.02 -bash
591 ttys000 0:00.01 bash /usr/local/bin/scala
// !! to get result as String
scala> "\\d+".r.findFirstIn( "ps" #| "grep /usr/local/bin/scala" !! )
res9: Option[String] = Some(591)
for a more information see: http://www.scala-lang.org/api/current/index.html#scala.sys.process.package 有关更多信息,请参阅: http : //www.scala-lang.org/api/current/index.html#scala.sys.process.package
When running Scala
on Java 9
, we can take advantage of Java
's ProcessHandle which makes it easier to identify and work with native processes: 在
Java 9
上运行Scala
时,我们可以利用Java
的ProcessHandle ,这样可以更轻松地识别和使用本机进程:
ProcessHandle.of(5210) match { case p => p.isPresent && p.get.isAlive }
where 5210 is the pid of the process you're interested in getting the status for. 其中5210是您有兴趣获取状态的过程的pid。
This: 这个:
First creates a Java Optional<ProcessHandle>
from the given pid
. 首先从给定的
pid
创建Java Optional<ProcessHandle>
。
If the process exists, this Optional
must be present
(which might be enough to tell if the process is alive depending on the system). 如果进程存在,这
Optional
必须present
(这可能足以告诉我们,如果过程取决于系统还活着)。
And finally checks that the process is alive using ProcessHandle::isAlive
. 最后使用
ProcessHandle::isAlive
检查进程是否处于活动状态。
No import necessary as ProcessHandle
is part of java.lang
. 由于
ProcessHandle
是java.lang
一部分,因此无需导入。
AFAIK, Java or Scala doesn't have such functionality. AFAIK,Java或Scala没有此类功能。 If you are on UNIX based machine, yes, your best bet is to use
ps
command. 如果您使用的是基于UNIX的计算机,是的,最好的办法是使用
ps
命令。
You can use the PID with ps
command as follows: 您可以使用PID with
ps
命令,如下所示:
ps -p 8238 -o "pid="
Here PID is 8283, and we ask ps
to search for it, and if it exists, just print it. 这里PID是8283,我们要求
ps
搜索它,如果它存在,只需打印它。
scala> import sys.process._
import sys.process._
scala> def processExists(pid: Int) = pid == {try { (List("ps", "-p", s"$pid", "-o", "pid=") !!).trim.toInt } catch { case _: Throwable => -1 }}
warning: there was one feature warning; re-run with -feature for details
processExists: (pid: Int)Boolean
scala> val pid = 8238
pid: Int = 8238
scala> processExists(pid)
res11: Boolean = true
scala> processExists(1234)
res12: Boolean = false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.