Handle Ctrl+C (Signal Interrupt) Close in the Terminal

· 372 words · 2 minutes read

When running a Go program in the terminal, your program could receive a signal interrupt from the OS for any number of reasons. One of which is if the user presses Ctrl+C on their keyboard (or whatever your operating system/terminal is set to). We can execute some code when this interrupt is received, mainly to clean up and reset what we were working on.

In our example we use a goroutine to listen for the interrupt from signal.Notify() (part of the signal package) and execute our clean up code when one is sent.

 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main

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

const FileNameExample = "go-example.txt"

func main() {

	// Setup our Ctrl+C handler
	SetupCloseHandler()

	// Run our program... We create a file to clean up then sleep
	CreateFile()
	for {
		fmt.Println("- Sleeping")
		time.Sleep(10 * time.Second)
	}
}

// SetupCloseHandler creates a 'listener' on a new goroutine which will notify the
// program if it receives an interrupt from the OS. We then handle this by calling
// our clean up procedure and exiting the program.
func SetupCloseHandler() {
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-c
		fmt.Println("\r- Ctrl+C pressed in Terminal")
		DeleteFiles()
		os.Exit(0)
	}()
}

// DeleteFiles is used to simulate a 'clean up' function to run on shutdown. Because
// it's just an example it doesn't have any error handling.
func DeleteFiles() {
	fmt.Println("- Run Clean Up - Delete Our Example File")
	_ = os.Remove(FileNameExample)
	fmt.Println("- Good bye!")
}

// Create a file so we have something to clean up when we close our program.
func CreateFile() {
	fmt.Println("- Create Our Example File")
	file, _ := os.Create(FileNameExample)
	defer file.Close()
}

This will output:

1
2
3
4
5
6
$ go run sigint.go 
- Create Our Example File
- Sleeping
- Ctrl+C pressed in Terminal
- Run Clean Up - Delete Our Example File
- Good bye!

And here’s what it looks like:

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!