捕获Go进程的终止代码?

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

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)手册页的说明:

信号SIGKILLSIGSTOP无法被捕获、阻塞或忽略。

英文:

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.

huangapple
  • 本文由 发表于 2014年11月19日 22:49:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/27019757.html
匿名

发表评论

匿名网友

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

确定