1

I got an application written in java which runs on Unix and starts two sub-processes (via Runtime.getRuntime().exec()) on startup. If the application crashed for some reason, the sub processes won't get killed.

Now, I added a shutdown hook which gets fired on every crash, ok so far. But I'd like to send a SIGTERM signal (or at least SIGINT) on UNIX console for every sub process of the application. I should be able to find their process IDs via ps, but I did not make it to extract the PID correctly and send a signal for every process.

Can anyone help?

Thank you very much!

Florian Müller
  • 7,448
  • 25
  • 78
  • 120
  • I am not sure but do what you want in a shell script i.e find process by supplying PID then kill that in shell script itself. Call this script in java. – Ved Apr 07 '12 at 06:41
  • if your application has a specific name, then pkill could work with that name. – tartar Apr 07 '12 at 06:43
  • another stub maybe here[1] http://blog.igorminar.com/2007/03/one-more-way-how-to-get-current-pid-in.html – tartar Apr 07 '12 at 06:43
  • The application does not have a specific name, the process is just named "java". But if get the process ID, how can I kill all subprocesses (in a shell script then)? – Florian Müller Apr 07 '12 at 07:08
  • 1
    Where does the shutdown hook run? If it is in Java, then did you try saving the `Process` objects and calling `destroy` on them? – Keith Randall Apr 07 '12 at 07:35
  • This seems a very good Idea ... I did not realize that the ShutdownHook is performed in the same JRE instance... Is this correct? In this case this would work. You could write this as answer and I'd mark it as correct :) – Florian Müller Apr 07 '12 at 07:49

1 Answers1

3

What I'm suggesting it is not an official feature, but a tricks.

This is how I get process id for my java applications. I never found another way.

public static final String getPid() {
    try {
        RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
        String name = runtimeBean.getName();
        int k = name.indexOf('@');
        if (k > 0)
            return name.substring(0, k);
    } catch (Exception ex) {
    }
    return null;
}

This works on win, mac and linux.

dash1e
  • 7,677
  • 1
  • 30
  • 35