如何捕捉 Ctrl+C 指令

背景

有时候在运行代码的时候,想要程序在接收到 Ctrl+C 指令的时候做一些平滑的处理,来写一下在 Python 和 Golang 中如何接收 Ctrl+C 指令。

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import signal
import time
import sys


def run_program():
while True:
print("Test code...")
time.sleep(1)


def exit_gracefully(signum, frame):
signal.signal(signal.SIGINT, original_sigint)
print("Receive Ctrl+C.")
sys.exit(1)


if __name__ == '__main__':
original_sigint = signal.getsignal(signal.SIGINT)
signal.signal(signal.SIGINT, exit_gracefully)
run_program()

Golang

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main

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

func WaitForCtrlC() {
var end_waiter sync.WaitGroup
end_waiter.Add(1)
var signal_channel chan os.Signal
signal_channel = make(chan os.Signal, 1)
signal.Notify(signal_channel, os.Interrupt)
go func() {
<-signal_channel
end_waiter.Done()
}()
end_waiter.Wait()
}

func testCode() {
for {
fmt.Println("Test code...")
time.Sleep(time.Duration(1) * time.Second)
}
}

func main() {
fmt.Printf("Press Ctrl+C to end\n")
go testCode()
WaitForCtrlC()
fmt.Printf("Receive Ctrl+C.\n")
}