本文整理汇总了Golang中os/signal.Stop函数的典型用法代码示例。如果您正苦于以下问题:Golang Stop函数的具体用法?Golang Stop怎么用?Golang Stop使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Stop函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: trapSignal
// trapSignal wait on listed signals for pre-defined behaviors
func (a *app) trapSignal(wg *sync.WaitGroup) {
ch := make(chan os.Signal, 10)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGHUP)
for {
sig := <-ch
switch sig {
case syscall.SIGTERM:
// this ensures a subsequent TERM will trigger standard go behaviour of terminating
signal.Stop(ch)
// roll through all initialized http servers and stop them
for _, s := range a.sds {
go func(s httpdown.Server) {
defer wg.Done()
if err := s.Stop(); err != nil {
a.errors <- probe.NewError(err)
}
}(s)
}
return
case syscall.SIGHUP:
// we only return here if there's an error, otherwise the new process
// will send us a TERM when it's ready to trigger the actual shutdown.
if _, err := a.net.StartProcess(); err != nil {
a.errors <- err.Trace()
}
}
}
}
示例2: WaitSignal
// WaitSignal waits for signals to gracefully terminate or restart the process.
// When code runs as a daemon process, it is often hoped running without any stop.
// So some works should be done on the flying.
// Some signals suggestion usage are listed herein.
func (gs *GraceServer) WaitSignal() error {
ch := make(chan os.Signal, 6)
signal.Notify(ch,
syscall.SIGTERM, // TERM : Exit immediatly
syscall.SIGINT, // INT : Exit immediatly
syscall.SIGQUIT, // QUIT : Exit gracefully
syscall.SIGHUP, // HUP : Gracefully reload configure and restart
// USR1 : Reopen log file
// USR2 : Update gracefully
// SIGWINCH : Exit worker process gracefully
// SIGSTOP, SIGKILL : Need not captured at anytime, process will quit immediatly
)
for {
sig := <-ch
switch sig {
case syscall.SIGTERM:
fallthrough
case syscall.SIGINT:
signal.Stop(ch)
return nil
case syscall.SIGQUIT:
signal.Stop(ch)
return gs.closeListener()
case syscall.SIGHUP:
// we only return here if there's an error, otherwise the new process
// will send us a TERM when it's ready to trigger the actual shutdown.
if err := gs.restart(); err != nil {
return err
}
}
}
}
示例3: Connect
func Connect(name, token string, factory Factory, config *ServerConfig) {
c, err := connect(name, token, factory, config)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(exitFail)
}
fmt.Fprintf(os.Stderr, "Connected bot %s. Ctrl-C or send SIGINT to disconnect.\n", name)
retryChan := make(chan time.Time)
cWait := func() {
c.conn.Wait()
retryChan <- time.Now()
}
go cWait()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGQUIT)
// Wait for either our connection with the server to terminate, or the user
// to mercilessly silence their bot.
loop:
for {
select {
case <-retryChan:
fmt.Fprintln(os.Stderr, "Lost connection to server, trying to reconnect...")
c, err = connect(name, token, factory, config)
if err == nil {
fmt.Fprintf(os.Stderr, "Reconnected bot %s successfully!\n", name)
// Wait until we lose the connection again
go cWait()
} else {
if strings.Contains(err.Error(), "connection refused") {
// If we can't connect, just wait ten (or --retry_interval) seconds and try again
go func() {
retryChan <- <-time.After(config.RetryInterval)
}()
} else {
// Fail on all other errors, like the server saying you have an invalid token
fmt.Fprintln(os.Stderr, err)
os.Exit(exitFail)
}
}
case <-sig:
signal.Stop(sig)
break loop
}
}
signal.Stop(sig)
fmt.Fprintln(os.Stderr, "Interrupted. Quitting...")
if c != nil {
if err := c.Close(); err != nil {
fmt.Fprintln(os.Stderr, "Error closing our connection:", err)
os.Exit(exitFail)
}
}
}
示例4: TestSignalsAreDeliveredToMultipleListeners
func TestSignalsAreDeliveredToMultipleListeners(t *testing.T) {
c1 := make(chan os.Signal, 1)
c2 := make(chan os.Signal, 1)
signal.Notify(c1, syscall.SIGWINCH)
signal.Notify(c2, syscall.SIGWINCH)
defer signal.Stop(c1)
defer signal.Stop(c2)
syscall.Kill(syscall.Getpid(), syscall.SIGWINCH)
waitSig(t, c1, syscall.SIGWINCH)
waitSig(t, c2, syscall.SIGWINCH)
}
示例5: main
func main() {
cli := CLI{}
config := cli.ParseArgs()
errs := config.Errors()
if len(errs) > 0 {
for _, e := range errs {
fmt.Println(e)
}
os.Exit(1)
}
if config.Debug {
log.Printf("Starting with config: %+v\n", config)
}
// shutdown signal handler; must be buffered, or risk missing the signal
// if we're not ready to receive when the signal is sent.
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
transport, err := flapjack.Dial(config.RedisServer, config.RedisDatabase)
if err != nil {
log.Fatalf("Couldn't establish Redis connection: %s\n", err)
}
finished := make(chan error)
api_client := ApiClient{config: config, redis: transport}
api_client.Connect(finished)
select {
case err := <-finished:
if config.Debug {
log.Printf("Finished with error // %s\n", err)
}
signal.Stop(sigs)
case <-sigs:
log.Println("Interrupted, cancelling request")
signal.Stop(sigs)
// TODO determine if request not currently active...
api_client.Cancel()
}
// close redis connection
transport.Close()
}
示例6: catchInterrupt
func catchInterrupt(quit chan int) {
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, os.Interrupt)
<-sigchan
signal.Stop(sigchan)
quit <- 1
}
示例7: setupStdin
// setupStdin switches out stdin for a pipe. We do this so that we can
// close the writer end of the pipe when we receive an interrupt so plugins
// blocked on reading from stdin are unblocked.
func setupStdin() {
// Create the pipe and swap stdin for the reader end
r, w, _ := os.Pipe()
originalStdin := os.Stdin
os.Stdin = r
// Create a goroutine that copies data from the original stdin
// into the writer end of the pipe forever.
go func() {
defer w.Close()
io.Copy(w, originalStdin)
}()
// Register a signal handler for interrupt in order to close the
// writer end of our pipe so that readers get EOF downstream.
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
go func() {
defer signal.Stop(ch)
defer w.Close()
<-ch
log.Println("Closing stdin because interrupt received.")
}()
}
示例8: signalHanlder
func signalHanlder() {
<-interrupt
signal.Stop(interrupt)
close(interrupt)
atomic.StoreInt32(&stop, 1)
}
示例9: AskString
// AskString asks user to input some string
func (cli CLI) AskString(query string, defaultStr string) (string, error) {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt)
defer signal.Stop(sigCh)
result := make(chan string, 1)
go func() {
fmt.Fprintf(cli.errStream, "%s [default: %s] ", query, defaultStr)
reader := bufio.NewReader(os.Stdin)
b, _, err := reader.ReadLine()
if err != nil {
Debugf("Failed to scan stdin: %s", err.Error())
}
line := string(b)
Debugf("Input: %q", line)
// Use Default value
if line == "" {
result <- defaultStr
}
result <- line
}()
select {
case <-sigCh:
return "", fmt.Errorf("interrupted")
case str := <-result:
return str, nil
}
}
示例10: main
func main() {
flag.Parse()
if err := embd.InitLED(); err != nil {
panic(err)
}
defer embd.CloseLED()
led, err := embd.NewLED(3)
if err != nil {
panic(err)
}
defer func() {
led.Off()
led.Close()
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, os.Kill)
defer signal.Stop(quit)
for {
select {
case <-time.After(250 * time.Millisecond):
if err := led.Toggle(); err != nil {
panic(err)
}
fmt.Println("Toggled")
case <-quit:
return
}
}
}
示例11: Wait
// Wait for signals to gracefully terminate or restart the process.
func (p *Process) Wait(listeners []Listener) (err error) {
ch := make(chan os.Signal, 2)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGUSR2)
for {
sig := <-ch
switch sig {
case syscall.SIGTERM:
signal.Stop(ch)
var wg sync.WaitGroup
wg.Add(len(listeners))
for _, l := range listeners {
go func(l Listener) {
defer wg.Done()
cErr := l.Close()
if cErr != nil {
err = cErr
}
}(l)
}
wg.Wait()
return
case syscall.SIGUSR2:
rErr := Restart(listeners)
if rErr != nil {
return rErr
}
}
}
}
示例12: AskForPassword
func (ui terminalUI) AskForPassword(prompt string, args ...interface{}) (passwd string) {
sig := make(chan os.Signal, 10)
// Display the prompt.
fmt.Println("")
fmt.Printf(prompt+PromptColor(">")+" ", args...)
// File descriptors for stdin, stdout, and stderr.
fd := []uintptr{os.Stdin.Fd(), os.Stdout.Fd(), os.Stderr.Fd()}
// Setup notifications of termination signals to channel sig, create a process to
// watch for these signals so we can turn back on echo if need be.
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGKILL, syscall.SIGQUIT,
syscall.SIGTERM)
defer signal.Stop(sig)
go catchSignal(fd, sig)
pid, err := echoOff(fd)
defer echoOn(fd)
if err != nil {
return
}
passwd = readPassword(pid)
// Carriage return after the user input.
fmt.Println("")
return
}
示例13: main
func main() {
if err := embd.InitGPIO(); err != nil {
panic(err)
}
defer embd.CloseGPIO()
pin, err := embd.NewAnalogPin(0)
if err != nil {
panic(err)
}
defer pin.Close()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, os.Kill)
defer signal.Stop(quit)
for {
select {
case <-time.After(100 * time.Millisecond):
val, err := pin.Read()
if err != nil {
panic(err)
}
fmt.Printf("reading: %v\n", val)
case <-quit:
return
}
}
}
示例14: handle
func handle(networkName string, netConn net.Conn) {
var wg sync.WaitGroup
fromServer := make(chan gauja.Message)
toServer := make(chan gauja.Message)
conn := MakeConn(networkName, netConn, fromServer, toServer)
conn.ControlLogger.Print("Connected to server")
gauja.NewBot(fromServer, toServer)
go func() {
interrupt := make(chan os.Signal)
defer signal.Stop(interrupt)
signal.Notify(interrupt, os.Interrupt)
<-interrupt
conn.ControlLogger.Print("Received interrupt")
conn.Terminate()
}()
wg.Add(3)
go func() {
defer wg.Done()
conn.handleFromServer()
}()
go func() {
defer wg.Done()
conn.handleToServer()
}()
go func() {
defer wg.Done()
<-conn.Terminated
}()
wg.Wait()
conn.ControlLogger.Print("Disconnected from server")
}
示例15: main
func main() {
flagStorage := cmdFlags{}
setupFlags(&flagStorage)
flag.Parse()
if flagStorage.debug {
go debugServer(DebugAddress)
}
// when the server starts print the version for debugging and issue logs later
logrus.Infof("Version: %s, Git commit: %s", version.NotaryVersion, version.GitCommit)
ctx, serverConfig, err := parseServerConfig(flagStorage.configFile, health.RegisterPeriodicFunc, flagStorage.doBootstrap)
if err != nil {
logrus.Fatal(err.Error())
}
c := utils.SetupSignalTrap(utils.LogLevelSignalHandle)
if c != nil {
defer signal.Stop(c)
}
if flagStorage.doBootstrap {
err = bootstrap(ctx)
} else {
logrus.Info("Starting Server")
err = server.Run(ctx, serverConfig)
}
if err != nil {
logrus.Fatal(err.Error())
}
return
}