zoukankan      html  css  js  c++  java
  • 1.11 程序优雅退出

    package main
    
    import (
    	"fmt"
    	"io"
    	"log"
    	"os"
    	"os/signal"
    	"syscall"
    	"time"
    )
    
    var writer *os.File
    
    func main() {
    
    	// The file is opened as
    	// a log file to write into.
    	// This way we represent the resources
    	// allocation.
    	var err error
    	writer, err = os.OpenFile(fmt.Sprintf("test_%d.log", time.Now().Unix()), os.O_RDWR|os.O_CREATE, os.ModePerm)
    	if err != nil {
    		panic(err)
    	}
    
    	// The code is running in a goroutine
    	// independently. So in case the program is
    	// terminated from outside, we need to
    	// let the goroutine know via the closeChan
    	closeChan := make(chan bool)
    	go func() {
    		for {
    			time.Sleep(time.Second)
    			select {
    			case <-closeChan:
    				log.Println("Goroutine closing")
    				return
    			default:
    				log.Println("Writing to log")
    				io.WriteString(writer, fmt.Sprintf("Logging access %s
    ", time.Now().String()))
    			}
    
    		}
    	}()
    
    	sigChan := make(chan os.Signal, 1)
    	signal.Notify(sigChan,
    		syscall.SIGTERM,
    		syscall.SIGQUIT,
    		syscall.SIGINT)
    
    	// This is blocking read from
    	// sigChan where the Notify function sends
    	// the signal.
    	<-sigChan
    
    	// After the signal is received
    	// all the code behind the read from channel could be
    	// considered as a cleanup
    	close(closeChan)
    	releaseAllResources()
    	fmt.Println("The application shut down gracefully")
    }
    
    func releaseAllResources() {
    	io.WriteString(writer, "Application releasing all resources
    ")
    	writer.Close()
    }
    
    /*
    
    2018/03/17 23:05:10 Writing to log
    2018/03/17 23:05:11 Writing to log
    2018/03/17 23:05:12 Writing to log
    2018/03/17 23:05:13 Writing to log
    The application shut down gracefully
    */
    
    
  • 相关阅读:
    [Python]计算豆瓣电影TOP250的平均得分
    [Golang]使用自建代理访问指定网站
    HDU 2689.Sort it-冒泡排序
    HDU 1728.逃离迷宫-BFS
    hihoCoder #1498.Diligent Robots
    POJ 2503.Babelfish-sscanf()函数+strcmp()函数+二分
    Codeforces 608 B. Hamming Distance Sum-前缀和
    Codeforces 608 A. Saitama Destroys Hotel
    sscanf()函数
    UVA 11461.Square Numbers
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8593465.html
Copyright © 2011-2022 走看看