Ubuntu Java: Find a specific program's pid and

2019-06-22 13:33发布

问题:

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

回答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.



回答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.



回答3:

you can use pidof to get the pid of your application

pidof <application name>



回答4:

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


回答5:

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


回答6:

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.



回答7:

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.



回答8:

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