github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/os/signal/example_unix_test.go (about)

     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  	"github.com/shogo82148/std/context"
    11  	"github.com/shogo82148/std/fmt"
    12  	"github.com/shogo82148/std/log"
    13  	"github.com/shogo82148/std/os"
    14  	"github.com/shogo82148/std/os/signal"
    15  )
    16  
    17  // This example passes a context with a signal to tell a blocking function that
    18  // it should abandon its work after a signal is received.
    19  func ExampleNotifyContext() {
    20  	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    21  	defer stop()
    22  
    23  	p, err := os.FindProcess(os.Getpid())
    24  	if err != nil {
    25  		log.Fatal(err)
    26  	}
    27  
    28  	// On a Unix-like system, pressing Ctrl+C on a keyboard sends a
    29  	// SIGINT signal to the process of the program in execution.
    30  	//
    31  	// This example simulates that by sending a SIGINT signal to itself.
    32  	if err := p.Signal(os.Interrupt); err != nil {
    33  		log.Fatal(err)
    34  	}
    35  
    36  	select {
    37  	case <-neverReady:
    38  		fmt.Println("ready")
    39  	case <-ctx.Done():
    40  		fmt.Println(ctx.Err()) // prints "context canceled"
    41  		stop()                 // stop receiving signal notifications as soon as possible.
    42  	}
    43  
    44  	// Output:
    45  	// context canceled
    46  }