devdotlog avatar

golang에서 signal 처리하기

ssh0702

Published: 20 Mar 2019 › Updated: 20 Mar 2019golang에서 signal 처리하기

golang에서 signal 처리하기

golang으로 console app을 개발하다보면 signal에 대한 처리가 필요한 경우가 있다. 예를 들어 동작 중인 console app을 CTRL+C 를 강제 종료하는 경우이다. 이런 경우에 interrupt를 발생시켜 종료하는 인데, interrupt에 대한 signal를 처리하여 app에서 필요한 처리를 마치고 종료 할수 가 있다.

다음 예제는 https://golang.org/pkg/os/signal/#example_Notify_allSignals 로 모든 signal을 수신하는 코드이다.

package main

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

func main() {
     // Set up channel on which to send signal notifications.
     // We must use a buffered channel or risk missing the signal
     // if we’re not ready to receive when the signal is sent.
     c := make(chan os.Signal, 1)
   
     // Passing no signals to Notify means that
     // all signals will be sent to the channel.
     signal.Notify(c)
   
     // Block until any signal is received.
     s := <-c
     fmt.Println(Got signal:, s)
}

code를 실행한 상태에서 CTRL+C를 이용하여 강제 종료를 시키면, 아래와 같이 console에 signal 로그가 출력된다.

Got signal: interrupt

하지만, kill PID, kill -SIGABRT PID를 이용하여 강제 종료를 하면, 해당 signal를 처리하지 못한다. 이런 부분을 처리하기 위해서는 channel과 range를 이용한다.

package main

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

func main() {
    channel := make(chan os.Signal, 1)
    
    signal.Notify(channel)
    
    for sig := range channel {
        fmt.Println("Got signal:", sig)
        os.Exit(1)
    }
}

Leave golang에서 signal 처리하기 to:

Written by

Read more #golang posts


Best Posts From devdotlog

We have not curated any of ssh0702's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From devdotlog