[Go] gocron source application to read -groutine the channel signal capture

Go directly function name () can open a grountine, channel information may be received and will block if no data is live
channel corresponding to a reference to the underlying data structures, copying function and channel parameters are passed by reference copy
make a second time parameter is 1, it means there is a cache of channel

Unbuffered channel, also known as synchronous channel

    c = make(chan interface{})
    //开启groutine
    go mySig()
    //主grountine不能断
    for {
        time.Sleep(time.Second)
        c <- "taoshihan"
    }
func mySig() {
    for {
        str := <-c
        fmt.Println(str)
    }
}

 

The signal processing using a communication channel

catchSignal FUNC () { 
    C: = the make (Chan os.Signal, . 1 ) 
    signal.Notify (C, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM) 
    for { 
        S: = <- C 
        logger.info ( " receive signal - " , S) 
        Switch S { 
        Case syscall.SIGHUP: 
            logger.info ( " receives OFF signal terminal, ignore " )
         Case syscall.SIGINT, syscall.SIGTERM: 
            the shutdown () 
        } 
    } 
}

Complete code:

package main

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

var c chan interface{}

func main() {
    go catchSignal()

    c = make(chan interface{})
    //开启groutine
    go mySig()
    //主grountine不能断
    for {
        time.Sleep(time.Second)
        c <- "taoshihan"
Func COZY () {
}
    }

    for { 
        STR: = <- C
         FMT .Println (STR) 
    } 
} 
FUNC catchSignal () { 
    D: = the make (Chan os.Signal, . 1 ) 
    signal.Notify (D, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM ) 
    for { 
        S: = <- D
         FMT .Println ( " the received signal - " , S) 
        Switch S { 
        Case syscall.SIGHUP:
             FMT .Println ( " receives OFF signal terminal, ignore " )
         Casesyscall.SIGINT, syscall.SIGTERM:
             // here you can do some exit action 
            fmt .Println ( " closed " ) 
            os.Exit ( 0 ) 
        } 
    } 
}

 

Guess you like

Origin www.cnblogs.com/taoshihan/p/11871405.html