java - 是否可以在 Windows 中编写忽略所有形式的 SIGTERM 的批处理 [或其他可执行] 应用程序

标签 java windows batch-file process sigterm

我正在尝试创建一个控制台应用程序,它以按 CTRL + BREAK 或向进程发送 SIGTERM 信号不会终止它的方式挂起[即它一直挂着,没有关闭]。我想测试它是否继续使用以下 Java 代码:

public static void main(String[] args) throws IOException {
//Replace APPLICATION PATH HERE with path towards the executable file
Process process = Runtime.getRuntime().exec("APPLICATION PATH HERE");
// this should kill the process
process.destroy();

// if the process is alive, exitValue() will throw exception
try {
  process.exitValue();
  // the process is dead - hasn't survived kill
  System.out.println("WRONG: process died");
} catch (IllegalThreadStateException e) {
  // the process is still running
  // the process is not dead and survived destroy()
  System.out.println("OK: process hanged");
}
}

到目前为止,我设法找到了以下信息: How Can I Make A Command Prompt Hang? ,虽然它不会停止 SIGTERM,只是 SIGINT。 我还尝试在 java -jar 可执行文件中使用 Shutdown Hooks,这也让我可以控制 SIGINT,但不能控制 SIGTERM。我希望程序在给出 SIGTERM 时继续运行,以便我测试 destroy 函数。 我还用 Go 编写了一个程序,它做类似的事情,除了它注册 CTRL+ BREAK 作为中断,出于某种原因[我不确定为什么,但它仍然不处理来自 java 代码的 SIGTERM 信号] :

package main

import "fmt"
import "os"
import "os/signal"
import "syscall"
func main() {
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)

go func() {
    sig := <-sigs
    fmt.Println("TEST!!")
    fmt.Println(sig)
    done <- true
}()
fmt.Println("awaiting signal")
<-done
sigs2 := make(chan os.Signal, 1)
done2 := make(chan bool, 1)
signal.Notify(sigs2, syscall.SIGTERM, syscall.SIGINT)
go func() {
    sig2 := <-sigs2
    fmt.Println("TEST!!")
    fmt.Println(sig2)
    done2 <- true
}()
fmt.Println("awaiting signal 2")
<-done2
}

注意:我仍然希望能够使用 SIGKILL 信号或窗口中的红色 X 关闭应用程序 :) 谢谢你的任何想法:)

最佳答案

来自Java API documentation (强调我的):

public abstract void destroy()

Kills the subprocess. The subprocess represented by this Process object is forcibly terminated.

在 Windows 术语中,这意味着它终止进程 - 相当于 SIGKILL。进程无法检测、防止或推迟终止。

请注意,Windows 没有任何与 SIGTERM 等效的东西。对于 GUI 应用程序,推荐的过程记录在 KB178893 中.

关于java - 是否可以在 Windows 中编写忽略所有形式的 SIGTERM 的批处理 [或其他可执行] 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33036919/

相关文章:

windows - cmd.exe |如何按特定格式统计文件数量?

windows - 将 IP 地址存储在变量中 - 与 Windows 版本无关

java - 动态加载 Java 类与实现 LUA

java.lang.VerifyError : main() threw exception :Incompatible argument to function

java - 在Java中,为什么@Nullable有运行时保留

Windows 批处理文件 : how to compare command line argument to an integer

java - Win Tomcat "Use default"JVM 错误

java - 使用 cellrendering 动态地将数据从数据库添加到 jtable 后,无法使用 JTable 进行排序操作

windows - 如何使用 Powershell 'invoke-expression' 以不同用户身份运行可执行文件

windows - 批处理文件如何删除自身并退出命令提示符?