如何从 Java 向外部进程发送 SIGINT 信号?
我有一个 Java 应用程序,它创建一个外部进程并通过 InputStream 读取该进程的标准输出。当我完成它时,我需要能够终止该进程。有没有办法向该进程发送 SIGINT 信号? (就像我从控制台按下 Ctrl+C 一样)。
外部进程不是我的代码,我无法修改它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将
kill -SIGINT
发送到进程吗(假设您知道进程 ID):当然,这将形成一个依赖于平台的解决方案...您可能会能够使用这个工具,尽管它处于“沙盒模式”。但它可能会给你一个想法:
http://commons.apache.org/sandbox/runtime/
另请参阅此处的相关问题:
我怎样才能杀死java 中的 Linux 进程使用 SIGKILL Process.destroy() 执行 SIGTERM
Can you send
kill -SIGINT <pid>
to the process (given that you know the process ID):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
对于从 Google 到达这里的其他人,如果您想将信号发送到当前进程(又名 JVM),您可以使用
sun.misc.Signal.raise()
方法。就我个人而言,我需要它是因为我正在使用 JNI 库。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.您是否将外部程序作为 java.lang.Process 运行?由于 Process 类有一个 destroy() 方法。
Are you running the external program as a
java.lang.Process
? As the Process class has adestroy()
method.不幸的是,Java 中没有发送任意信号的本机方法。
我同意 Lukas 使用 Runtime.exec() 的观点,或者你可以使用类似 Posix for Java< /a> 库。
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.