How to send SIGINT signal from Java to an external process?

放肆的年华 提交于 2019-11-29 11:26:24

问题


I have a Java app that creates an external process and reads the process' stdout through an InputStream. I need to be able to kill the process when I am done with it. Is there a way to send a SIGINT signal to this process? (as if I pressed Ctrl+C from the console).

The external process is not my code and I cannot modify it.


回答1:


Are you running the external program as a java.lang.Process? As the Process class has a destroy() method.




回答2:


Can you send kill -SIGINT <pid> to the process (given that you know the process ID):

Runtime.getRuntime().exec("kill -SIGINT 12345");

Of course, that would make for a platform-dependent solution... Potentially, you'll be able to use this tool, although it is in "sandbox mode". But it might give you an idea:

http://commons.apache.org/sandbox/runtime/

See also this related question here:

how can I kill a Linux process in java with SIGKILL Process.destroy() does SIGTERM




回答3:


For other people arriving here from Google if you want to send the signal to the current Process (aka JVM) you can use sun.misc.Signal.raise() method. Personally I need it because of a JNI library that I am using.




回答4:


Unfortunately there isn't a native way to send an arbirtray signal in Java.

I agree with Lukas in using Runtime.exec() or you could use something like Posix for Java library.



来源:https://stackoverflow.com/questions/7835212/how-to-send-sigint-signal-from-java-to-an-external-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!