是否可以仅记录接收到的每个信号而不改变行为?

时间:2019-03-19 07:29:13

标签: go signals

我知道如何捕捉每个信号

idleConnsClosed := make(chan bool)
SignalChannel := make(chan os.Signal, 1)

// Notify to SignalChannel any signal received
signal.Notify(SignalChannel)

go func() {
    for {
        sig := <-SignalChannel
        log.Notice("Signal %#v received", sig)
        switch sig {
        case syscall.SIGTERM:
            // ok sigterm, I know how to handle with it
            log.Info("ShutDown HTTP server (SIGTERM)")
            if err := server.Shutdown(context.Background()); err != nil {
                // Error from closing listeners, or context timeout:
                log.Error("HTTP server Shutdown: %v", err)
            }
        case syscall.SIGHUP:
            //reinit configurations and do some stuff, I know how to handle this                 
            continue
        case syscall.SIGPIPE:
            //Don't know what to do, just wanted to log it
            continue
        case syscall.SIGABRT:
            //exit with core dump...how to do that ?
            continue
        default:
            // unhandled signal?, ok how to not change it's behavior?
            log.Warning("Unhandled Signal %s received!", sig)
        }
        close(idleConnsClosed)
    }
}()

一般来说,我只是想

  1. 处理一些可以理解的信号-X
  2. 记录我收到的每个信号-Y
  3. 不要更改Y-X信号的行为

2 个答案:

答案 0 :(得分:1)

Notify禁用给定一组异步信号的默认行为,而是通过一个或多个已注册通道传递它们。我认为这意味着您必须在不改变信号行为的情况下拦截信号。

docs描述了默认行为:

  

默认情况下,同步信号会转换为运行时紧急情况。 SIGHUP,SIGINT或SIGTERM信号导致程序退出。 SIGQUIT,SIGILL,SIGTRAP,SIGABRT,SIGSTKFLT,SIGEMT或SIGSYS信号导致程序退出并带有堆栈转储

应该有可能捕获信号,对其进行处理,然后模拟适合该信号的默认行为。

答案 1 :(得分:0)

我认为您想要以下代码。该代码只有一个框架。

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"
)

func main() {
    done := make(chan bool)
    channel := make(chan os.Signal, 1)

    signal.Notify(channel)

    go func() {
        for sig := range channel {

            switch sig {
            case syscall.SIGTERM:
                fmt.Printf("SIGTERM Signal %s received!\n", sig)
            case syscall.SIGHUP:
                fmt.Printf("SIGHUP Signal %s received!\n", sig)
            case syscall.SIGPIPE:
                fmt.Printf("SIGPIPE Signal %s received!\n", sig)
            case syscall.SIGABRT:
                fmt.Printf("SIGABRT Signal %s received!\n", sig)
            default:
                fmt.Printf("Unhandled Signal %s received!\n", sig)
                done <- true
            }
        }
    }()

    <-done
}

代码已更新。