6

I hear in java 9 they did a lot of work updating the Process API. Is there now a cleaner way to send a signal to a Process spawned by Java? The signals are used as a simple way to trigger actions in the process.

Before I had to use reflection to get a pid and then use Runtime#exec to send the kill command. I assume you still need to use Runtime#exec because signal may be OS dependent, but I'm curious if anyone knows a better way than this!

Process p = Runtime.getRuntime().exec(...);
...
Runtime.getRuntime().exec("kill -SIGUSR1 " + p.getPid());
Whymarrh
  • 13,139
  • 14
  • 57
  • 108
flakes
  • 21,558
  • 8
  • 41
  • 88
  • 3
    You could look at the doc: http://download.java.net/java/jdk9/docs/api/java/lang/Process.html The only obvious things I can see are `destroy` and `destroyForcibly`, but those were there already in Java 8. – Jorn Vernee Feb 21 '17 at 22:04
  • @JornVernee yup that's where I saw `getPid` from. Just wondering if I missed anything! – flakes Feb 21 '17 at 22:11
  • Possible duplicate of [How to send SIGINT signal from Java to an external process?](http://stackoverflow.com/questions/7835212/how-to-send-sigint-signal-from-java-to-an-external-process) – Whymarrh Feb 28 '17 at 03:37
  • 1
    Unfortunately where Windows doesn't have signals this isn't something Java can expose cross-platform so your best bet is something like jnr-posix, though it won't work on Windows [\[1\]](https://github.com/jnr/jnr-posix/blob/c3ed9095db6eaf1c7ff65dc398c6cbaff7760e2f/src/main/java/jnr/posix/WindowsPOSIX.java#L151-L163). – Whymarrh Feb 28 '17 at 03:39

1 Answers1

3

signal may be OS dependant

Yes, windows does not have signals in the same sense posix OSes do.

but I'm curious if anyone knows a better way than this!

jnr-posix provides thin wrappers around libc, including kill.

the8472
  • 40,999
  • 5
  • 70
  • 122