Ubuntu Java: Find a specific program's pid and kill the program

14,375

Solution 1

You might try ps -aux | grep foobar for getting the pid, then issuing the kill command against it, alternatively you might want to use pkillfoobar, in both cases foobar being the name of the app you want to terminate.

Solution 2

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.

Solution 3

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();
    }
}
}

Solution 4

you can use pidof to get the pid of your application

pidof <application name>

Solution 5

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.

Share:
14,375

Related videos on Youtube

Abraham Miguel Espiritu
Author by

Abraham Miguel Espiritu

Updated on June 04, 2022

Comments

  • Abraham Miguel Espiritu
    Abraham Miguel Espiritu almost 2 years

    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