Home  >  Article  >  Backend Development  >  Is it possible to catch the Ctrl+C signal (SIGINT) and run the cleanup function in a "deferred" manner?

Is it possible to catch the Ctrl+C signal (SIGINT) and run the cleanup function in a "deferred" manner?

PHPz
PHPzforward
2024-02-08 23:18:331054browse

是否可以捕获 Ctrl+C 信号 (SIGINT) 并以“延迟”方式运行清理函数?

php Xiaobian Yuzai will answer a common question for everyone in this article: "Is it possible to capture the Ctrl C signal (SIGINT) and run the cleanup function in a 'delayed' manner? ?" When writing PHP scripts, we often need to handle some cleanup operations, such as closing database connections, releasing resources, etc. When the user presses the Ctrl C key combination, the system interrupt signal SIGINT is triggered, causing the script to terminate immediately. But what if we want to perform some cleanup before the script is terminated? Let’s discuss it together!

Question content

I want to capture the Ctrl C (SIGINT) signal sent from the console and print out some parts Running total.

Workaround

You can use the os/signal package to handle incoming signals. ctrl c is sigint so you can use it to catch 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 way you make the program terminate and print the information is entirely up to you.

The above is the detailed content of Is it possible to catch the Ctrl+C signal (SIGINT) and run the cleanup function in a "deferred" manner?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete