maksadbek
maksadbek

Reputation: 1592

Go app cannot catch signals

Sending signals from kill on linux, kill -s 2 <PID> or kill -s 15 <PID>

The code is:

package main

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

func main() {
    sigs := make(chan os.Signal, 1)
    done := make(chan bool, 1)
    signal.Notify(sigs)
    go func() {
        sig := <-sigs
        fmt.Println(sig)
    }()
    fmt.Println("waiting")
    <-done
    fmt.Println("exiting")
}

The program does not handle signals, only CTRL+C works well.

Upvotes: 3

Views: 556

Answers (1)

Alper
Alper

Reputation: 13220

func() is terminated after receiving the first signal, I think CTLR+C was the first one when you try. It works when it is wrapped in a loop.

package main

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

func main() {
    sigs := make(chan os.Signal, 1)
    done := make(chan bool, 1)
    signal.Notify(sigs)
    go func() {
        for {
            sig := <-sigs
            fmt.Println(sig)
        }
    }()
    fmt.Println("waiting")
    <-done
    fmt.Println("exiting")
}

Tested with;

$ kill -15 <pid>
$ kill -2 <pid>
$ kill -10 <pid>
$ kill -1 <pid>
$ kill -10 <pid>

$ ./signal 
waiting
terminated
interrupt
user defined signal 1
hangup
user defined signal 1

Upvotes: 1

Related Questions