сигналы

This commit is contained in:
badkaktus 2019-10-12 22:01:03 +03:00
parent 653625e88a
commit c232a309a6
3 changed files with 27 additions and 23 deletions

View File

@ -70,5 +70,5 @@ HTTP клиенты (HTTP Clients)
HTTP серверы (HTTP Servers) HTTP серверы (HTTP Servers)
Порождающие процессы (Spawning Processes) Порождающие процессы (Spawning Processes)
Исполняющие процессы (Exec'ing Processes) Исполняющие процессы (Exec'ing Processes)
Signals Сигналы (Signals)
Exit Exit

View File

@ -1,9 +1,10 @@
// Sometimes we'd like our Go programs to intelligently // Иногда нам хотелось бы, чтобы наши программы на Go
// handle [Unix signals](http://en.wikipedia.org/wiki/Unix_signal). // интеллектуально обрабатывали [сигналы Unix](http://en.wikipedia.org/wiki/Unix_signal).
// For example, we might want a server to gracefully // Например, мы можем захотеть, чтобы сервер корректно
// shutdown when it receives a `SIGTERM`, or a command-line // завершил работу при получении `SIGTERM`, или инструмент
// tool to stop processing input if it receives a `SIGINT`. // командной строки остановил обработку ввода, если он
// Here's how to handle signals in Go with channels. // получил `SIGINT`. Вот как обрабатывать сигналы в Go
// с каналами.
package main package main
@ -16,20 +17,21 @@ import (
func main() { func main() {
// Go signal notification works by sending `os.Signal` // Уведомление о выходе сигнала работает путем
// values on a channel. We'll create a channel to // отправки значений `os.Signal` в канал. Мы создадим
// receive these notifications (we'll also make one to // канал для получения этих уведомлений (мы также
// notify us when the program can exit). // создадим канал, чтобы уведомить нас, когда программа
// может выйти).
sigs := make(chan os.Signal, 1) sigs := make(chan os.Signal, 1)
done := make(chan bool, 1) done := make(chan bool, 1)
// `signal.Notify` registers the given channel to // `signal.Notify` регистрирует данный канал для
// receive notifications of the specified signals. // получения уведомлений об указанных сигналах.
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// This goroutine executes a blocking receive for // Эта горутина выполняет блокировку приема сигналов.
// signals. When it gets one it'll print it out // Когда она получит его, то распечатает его, а
// and then notify the program that it can finish. // затем уведомит программу, что она может быть завершена.
go func() { go func() {
sig := <-sigs sig := <-sigs
fmt.Println() fmt.Println()
@ -37,9 +39,10 @@ func main() {
done <- true done <- true
}() }()
// The program will wait here until it gets the // Программа будет ждать здесь, пока не получит
// expected signal (as indicated by the goroutine // ожидаемый сигнал (как указано в приведенной
// above sending a value on `done`) and then exit. // выше процедуре, отправляющей значение в `done`),
// и затем завершится.
fmt.Println("awaiting signal") fmt.Println("awaiting signal")
<-done <-done
fmt.Println("exiting") fmt.Println("exiting")

View File

@ -1,7 +1,8 @@
# When we run this program it will block waiting for a # Когда мы запустим эту программу, она заблокирует
# signal. By typing `ctrl-C` (which the # ожидание сигнала. Набрав `ctrl-C` (который терминал
# terminal shows as `^C`) we can send a `SIGINT` signal, # показывает как `^C`), мы можем послать сигнал `SIGINT`,
# causing the program to print `interrupt` and then exit. # в результате чего программа напечатает `interrupt`
# и затем выйдет.
$ go run signals.go $ go run signals.go
awaiting signal awaiting signal
^C ^C