如何在Windows上使golang信号处理程序正常工作

huangapple go评论80阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;os/signal&quot;
	&quot;syscall&quot;
	&quot;time&quot;
)

func main() {
	detectShutdown()
	fmt.Println(&quot;Running&quot;)
	time.Sleep(5 * time.Second)
}

func detectShutdown() {
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT)
	go func() {
		sig := &lt;-sigChan
		fmt.Printf(&quot;Signal [%s] detected\n&quot;, 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.

huangapple
  • 本文由 发表于 2022年7月22日 01:24:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/73070367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定