Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graceful kill of Apache Commons Exec process

I am starting an external process in my Java program (on Linux) and I need the ability to send it a SIGTERM signal rather than the SIGKILL that exec.getWatchdog().destroyProcess() is sending. Is there a way that I can more gracefully stop a unix process started with commons-exec? Or can I get the PID so that I can just run the appropriate kill command myself?

like image 332
jtb Avatar asked Mar 02 '11 22:03

jtb


2 Answers

ExecuteWatchdog class has method for killing process.

So, you could just create a watchdog with long timeout and use it to kill process when neccessary, i.e.

executor.getWatchdog().destroyProcess();
like image 153
audras Avatar answered Oct 18 '22 14:10

audras


Well, Commons Exec relies on the Java Process class, which doesn't expose a PID. It's also what is used to kill the process, so it's not something you can change the behavior of. All nice and encapsulated. Gotta love OO, eh?

If you are simply launching processes in to the background, you can wrap them in a simple shell script that captures the PID for you, and then saves that off to a "known place" that your Java routine knows about. Still kind of messy, and, naturally, it doesn't port to other platforms well.

You can write your own exec function using JNI to capture this information for you as well, but that's likely less friendly.

You could write a platform specific exec launcher daemon in something more system oriented (C, Python, etc.). You send IT messages to launch and stop things, and it handles that process for you. One benefit of this is that you don't have to fork the JVM when you run a new process (which can be quite expensive depending on your JVM size).

You can start the daemon up at the beginning and share a socket or a pipe (both pretty portable). That's actually not a horribly INelegant solution, and it compartmentalizes a lot of system specific behavior (so you can have a completely different process on, say, Windows vs Unix and your Java stays the same, you just need to port your little daemon), without having to run JNI.

like image 32
Will Hartung Avatar answered Oct 18 '22 16:10

Will Hartung