How to intercept Ctrl+C (SIGINT) and perform resource cleanup in Go, like with defer?
Hello everyone! I'm writing a server application in Go that opens TCP connections, works with files and a database. I need the program to gracefully shut down when Ctrl+C (SIGINT signal) is pressed: close connections, save data, release resources.\n\nI know about `defer` — it works perfectly when a function exits normally. But when I press Ctrl+C, the program just gets killed, and `defer` doesn't execute. For example:\n\n```go\nfunc main() {\n db, _ := sql.Open("postgres", "...")\n defer db.Close()\n\n // some infinite loop\n for {\n // working\n }\n}\n```\n\nWhen Ctrl+C is pressed, `defer db.Close()` doesn't execute. I've read about the `os/signal` package, but I don't understand how to properly organize "defer-like" behavior. How can I make it so that under any
No answers yet.
Log in to leave an answer