I need to check if a specified process is currently running using Scala.
All I have is the PID.
Does Scala have an internal function or do I need to parse it using ps
?
Thank you.
AFAIK, Java or Scala doesn't have such functionality. If you are on UNIX based machine, yes, your best bet is to use ps
command.
You can use the PID with ps
command as follows:
ps -p 8238 -o "pid="
Here PID is 8283, and we ask ps
to search for it, and if it exists, just print it.
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