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
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
You might try ps -aux | grep foobar
for getting the pid, then issuing the kill
command against it, alternatively you might want to use pkill
foobar
, in both cases foobar
being the name of the app you want to terminate.
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.
you can use pidof
to get the pid of your application
pidof <application name>
How about this then?
public static void killAll(String process) {
try {
Vector<String> commands = new Vector<String>();
commands.add("pidof");
commands.add(process);
ProcessBuilder pb = new ProcessBuilder(commands);
Process pr = pb.start();
pr.waitFor();
if (pr.exitValue() != 0) return;
BufferedReader outReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
for (String pid : outReader.readLine().trim().split(" ")) {
log.info("Killing pid: "+pid);
Runtime.getRuntime().exec("kill " + pid).waitFor();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
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:
nohup java -jar example.jar &
echo $! > application.pid
ps aux | awk '/java/ {print "sleep 10; kill "$2}' | bash
in Ubuntu, ps -aux
throws an syntax error, where ps 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.
You'll probably have to invoke the ps
and kill
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.
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