英文:
How to make golang signal handler working on windows
问题
以下是翻译好的内容:
以下测试程序在我的Linux机器上正常工作,但在我的Windows机器上不起作用。
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
detectShutdown()
fmt.Println("Running")
time.Sleep(5 * time.Second)
}
func detectShutdown() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT)
go func() {
sig := <-sigChan
fmt.Printf("Signal [%s] detected\n", sig)
os.Exit(1)
}()
}
在Linux上的输出结果:
Running
^CSignal [interrupt] detected
在Windows上的输出结果:
Running
有人知道如何使其在Windows上工作吗?谢谢。
英文:
The following test program is working fine on my linux machine, but it is not working on my windows machine
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
detectShutdown()
fmt.Println("Running")
time.Sleep(5 * time.Second)
}
func detectShutdown() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT)
go func() {
sig := <-sigChan
fmt.Printf("Signal [%s] detected\n", sig)
os.Exit(1)
}()
}
Output on linux
Running
^CSignal [interrupt] detected
Output on Windows
Running
Anyone has idea on how to make it works on Windows? Thanks
答案1
得分: 2
问题在于Windows不支持POSIX(Unix)信号作为一种支持的IPC形式。在控制台应用程序中处理Ctrl-C
(和Ctrl-Break
)键盘组合在Windows上与在运行附加到Unix兼容终端和终端仿真器的程序中处理方式完全不同。
自从一段时间以来,Go在os/signal
中获得了对Windows的支持,以一种特殊的信号os.Interrupt
的形式。在POSIX兼容系统上,它是os.SIGINT
的别名(并且以通常的方式进行处理),而在Windows上,它不代表任何信号(因为它们不存在),但是当用户按下上述键盘组合时会模拟该信号。
我建议您实际阅读os/signal
包的文档,特别是它的名为“Windows”的部分。提前这样做可以节省您和我询问和回答一个无关紧要问题的时间。
英文:
The problem is that Windows does not have POSIX (Unix) signals as a form of supported IPC. Handling Ctrl-C
(and Ctrl-Break
) keyboard combinations in console applications is done completely different on Windows than it is done in programs running attached to Unix-compatible terminals and terminal emulators.
Since some time Go has gained support in os/signal
for Windows in the form of a special signal os.Interrupt
, which, on POSIX-compatible systems is an alias for os.SIGINT
(and is processed in the usual way), and on Windows it does not stand for any signal (for their lack thereof) but is emulated when the user presses the keyboard combinations mentioned above.
I advise you to actually read the docs of the os/signal
package—especially its section called "Windows". Doing this up-front would have saved you and me spending time asking and answering a question about a non-problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论