是否有可能捕获Ctrl + C信号并运行清理功能,以“延迟”时尚? [英] Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

查看:98
本文介绍了是否有可能捕获Ctrl + C信号并运行清理功能,以“延迟”时尚?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕获控制台发送的 Ctrl + C SIGINT )信号并打印出部分运行总数。

I want to capture the Ctrl+C (SIGINT) signal sent from the console and print out some partial run totals.

这可能在Golang中吗?

Is this possible in Golang?

注意:当我第一次发布这个问题时,我对 Ctrl + C SIGTERM 而不是 SIGINT

Note: When I first posted the question I was confused about Ctrl+C being SIGTERM instead of SIGINT.

推荐答案

您可以使用操作系统/信号包来处理传入的信号。 ^ C是 SIGINT ,因此您可以使用它来捕获 os.Interrupt

You can use the os/signal package to handle incoming signals. ^C is SIGINT, so you can use this to trap os.Interrupt.

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func(){
    for sig := range c {
        // sig is a ^C, handle it
    }
}()

您的程序终止并打印信息的方式完全取决于您。

The manner in which you cause your program to terminate and print information is entirely up to you.

这篇关于是否有可能捕获Ctrl + C信号并运行清理功能,以“延迟”时尚?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆