7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

golangでシグナルを拾ってgracefulにgoroutineを停めたい

Last updated at Posted at 2015-11-04

golangでシグナルを拾ってgracefulにgoroutineを停めたい

とりあえず SIGHUP をトラップしてみる。

…全然カンタンじゃない。
もうちょいなんとかならないのかと思うけど、とりあえずこれで上手くいってそうな気がする。

=> 続き
http://qiita.com/arc279/items/6154919702b2fa408c72

main.go
package main

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

func main() {

	procs := []string{
		"proc1",
		"proc2",
		"proc3",
		"proc4",
		"proc5",
		"proc6",
		"proc7",
	}

	ch := make([]chan int, len(procs))
	for i, _ := range ch {
		ch[i] = make(chan int)
	}

	var wg sync.WaitGroup
	// goroutine起動
	for i, id := range procs {
		wg.Add(1)
		go func(ch chan int, id string) {
			cnt := 0
			fmt.Println("start " + id)
			for {
				select {
				case sig := <-ch:
					fmt.Println(sig)
					wg.Done()
					break
				default:
					// 何らかの平行処理したいやつ
					cnt++
					fmt.Println(fmt.Sprintf("%s>> %d", id, cnt))
					time.Sleep(500 * time.Millisecond)
				}
			}
		}(ch[i], id)
	}

	// HUP シグナルをトラップ
	signal_chan := make(chan os.Signal, 1)
	signal.Notify(signal_chan,
		syscall.SIGHUP,
	)
	go func() {
		for {
			switch <-signal_chan {
			case syscall.SIGHUP:
				fmt.Println("hungup")
				for _, c := range ch {
					c <- 1
				}
			}
		}
	}()

	// goroutine終了を待ち合わせ
	wg.Wait()

	fmt.Println("stop gracefully")
	os.Exit(0)
}

ビルドして実行

$ go build -o sample main.go && ./sample

シグナル送る

別の端末から

$ kill -SIGHUP `pgrep -f sample`
7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?