Source file src/os/signal/example_unix_test.go

     1  // Copyright 2020 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build unix
     6  
     7  package signal_test
     8  
     9  import (
    10  	"context"
    11  	"fmt"
    12  	"log"
    13  	"os"
    14  	"os/signal"
    15  )
    16  
    17  var neverReady = make(chan struct{}) // never closed
    18  
    19  // This example passes a context with a signal to tell a blocking function that
    20  // it should abandon its work after a signal is received.
    21  func ExampleNotifyContext() {
    22  	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    23  	defer stop()
    24  
    25  	p, err := os.FindProcess(os.Getpid())
    26  	if err != nil {
    27  		log.Fatal(err)
    28  	}
    29  
    30  	// On a Unix-like system, pressing Ctrl+C on a keyboard sends a
    31  	// SIGINT signal to the process of the program in execution.
    32  	//
    33  	// This example simulates that by sending a SIGINT signal to itself.
    34  	if err := p.Signal(os.Interrupt); err != nil {
    35  		log.Fatal(err)
    36  	}
    37  
    38  	select {
    39  	case <-neverReady:
    40  		fmt.Println("ready")
    41  	case <-ctx.Done():
    42  		fmt.Println(ctx.Err()) // prints "context canceled"
    43  		stop()                 // stop receiving signal notifications as soon as possible.
    44  	}
    45  
    46  	// Output:
    47  	// context canceled
    48  }
    49  

View as plain text