Help us understand the problem. What is going on with this article?

Goで受け取ったシグナルによって動きを変えたい

More than 3 years have passed since last update.

Goでシグナルを受け取ってゴニョゴニョしたくなったとします。SIGINTSIGTERMを受け取ったら終了してSIGUSR1を受け取ったらそのことを通知するようなGoのプログラムは以下の様な感じで書けました。

package main

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

func main() {
    c := make(chan os.Signal, 1)
    ec := make(chan int)
    signal.Notify(c, syscall.SIGTERM, syscall.SIGINT, syscall.SIGUSR1)

    go func() {
        for {
            switch <-c {
            case syscall.SIGTERM:
                ec <- 0
            case syscall.SIGINT:
                ec <- 0
            case syscall.SIGUSR1:
                log.Println("SIGUSR1!")
            }
        }
    }()

    <-ec
}

シグナルが来る時にメモリを確保しないようにチャネルcのサイズを指定しています。printしているところに何か処理を書けばSIGUSR1シグナルを受け取ったらいい感じにするプログラムが書けると思います。

別途PIDファイルを作りたい場合は以下の記事を参考にしてください。

Go製のサーバーで起動時にPIDファイルを作る - Qiita

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away