英文:
Capturing kill code of go process?
问题
我正在尝试编写一个测试,以测试kill命令的功能。为了做到这一点,我需要我的测试目标(一个非常简单的Go HTTP服务器-https://github.com/jadekler/git-grunt-gostop/blob/master/test/fixtures/gostop_basic.go)能够区分使用-2和-9进行kill的情况。有没有什么方法可以做到这一点?似乎无论是-2还是-9,Go的defer都不会发生,这是我第一次尝试的方法。后续的研究并没有给出明确的答案。
谢谢任何建议!
英文:
I'm trying to write a test that would drive out functionality for kill commands. To do this, I need the target of my test (a very simple go http server - https://github.com/jadekler/git-grunt-gostop/blob/master/test/fixtures/gostop_basic.go) to differentiate between having been killing with -2 vs -9. Is there some way to do this? It seems as though go's defer doesn't happen regardless of -2 vs -9, which was my first try. Subsequent research has not been enlightening.
Thanks for any suggestions!
答案1
得分: 5
你可以使用os/signal
包来捕获信号。你可以使用以下代码来捕获SIGINT
信号:
import (
"os"
"os/signal"
)
...
// 如果通道没有准备好接收,信号模块将丢失通知,所以给它一个缓冲区
ch := make(chan os.Signal, 5)
go func() {
for sig := range ch {
// 收到中断信号
os.Exit(0)
}
}()
signal.Notify(ch, os.SIGINT)
不幸的是,你不能对SIGKILL
做同样的操作。根据signal(7)
手册页的说明:
信号
SIGKILL
和SIGSTOP
无法被捕获、阻塞或忽略。
英文:
You can catch signals using the os/signal
package. You can catch SIGINT
with code something like this:
import (
"os"
"os/signal"
)
...
// the signal module will lose notifications if the channel is not ready to receive, so give it a buffer
ch := make(chan os.Signal, 5)
go func() {
for sig := range ch {
// interrupt signal received
os.Exit(0)
}
}()
signal.Notify(ch, os.SIGINT)
Unfortunately, you can't do the same for SIGKILL
. From the signal(7)
man page:
> The signals SIGKILL
and SIGSTOP
cannot be caught, blocked, or ignored.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论