signals

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 17, 2025 License: Apache-2.0 Imports: 5 Imported by: 0

README

signals

signals is a Go module that provides utilities for handling OS signals.

Go Reference Go Report Card

This package offers functionality to create contexts that can be canceled when specific OS signals are received, making it easier to implement graceful shutdown or interruption handling in applications.

The key feature is NotifyContext, which creates a context that is canceled when one of the specified signals is received, and executes a function with that context. The signal that caused cancellation can be retrieved using FromContext.

Installation

To install the signals module, use the following command:

go get github.com/goaux/signals

Usage

func NotifyContext and FromContext

NotifyContext creates a context that is canceled when a signal is received, and runs a provided function with that context. The result of the function is returned as is, regardless of whether it is an error.

FromContext can be used with the context to retrieve the signal that caused cancellation. context.Cause can also be used to retrieve the signal within Canceled.

package main

import (
	"context"
	"fmt"
	"os"
	"time"

	"github.com/goaux/signals"
	"github.com/goaux/stacktrace/v2"
	"github.com/goaux/timer"
)

func main() {
	ctx := context.Background()
	err := signals.NotifyContext(ctx, run, os.Interrupt)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", stacktrace.Format(err))
		os.Exit(1)
	}
}

func run(ctx context.Context) error {
	if err := timer.SleepCause(ctx, 7*time.Second); err != nil {
		if sig, ok := signals.FromContext(ctx); ok {
			fmt.Printf("Context was canceled by signal: %v\n", sig)
			return nil
		}
		return err
	}
	fmt.Println("hello")
	return nil
}
func Wait

Here's a basic example of how to use the Wait function from the signals package:

package main

import (
	"context"
	"fmt"
	"syscall"
	"time"

	"github.com/goaux/signals"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
	defer cancel()

	fmt.Println("Waiting for SIGINT or SIGTERM...")
	sig := signals.Wait(ctx, syscall.SIGINT, syscall.SIGTERM)

	if sig != nil {
		fmt.Printf("Received signal: %v\n", sig)
	} else {
		fmt.Println("Context canceled")
	}
}

This example waits for either SIGINT or SIGTERM for up to one minute. If a signal is received, it prints the signal. If the context is canceled (in this case, due to timeout), it prints "Context canceled".

Documentation

Overview

Package signals provides utilities for handling OS signals in Go applications.

This package offers functionality to create contexts that can be canceled when specific OS signals are received, making it easier to implement graceful shutdown or interruption handling in applications.

The key feature is NotifyContext, which creates a context that is canceled when one of the specified signals is received, and executes a function with that context. The signal that caused cancellation can be retrieved using FromContext.

Example (NotifyContext)
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"syscall"

	"github.com/goaux/signals"
)

func main() {
	ctx := context.Background()
	err := signals.NotifyContext(ctx, runN, syscall.SIGINT, syscall.SIGTERM)
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
}

func runN(ctx context.Context) error {
	fmt.Println(ctx)
	syscall.Kill(os.Getpid(), syscall.SIGINT)
	<-ctx.Done()
	err := context.Cause(ctx)
	fmt.Println(err.Error())
	fmt.Println(errors.Is(err, context.Canceled))
	fmt.Println(signals.FromContext(ctx))
	return nil
}
Output:

signals.NotifyContext(context.Background, [interrupt terminated])
context canceled (interrupt)
true
interrupt true
Example (Wait)
package main

import (
	"context"
	"fmt"
	"syscall"
	"time"

	"github.com/goaux/signals"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	fmt.Println("Waiting for SIGINT or SIGTERM...")
	sig := signals.Wait(ctx, syscall.SIGINT, syscall.SIGTERM)

	if sig != nil {
		fmt.Printf("Received signal: %v\n", sig)
	} else {
		fmt.Println("Context canceled")
	}
}
Output:

Waiting for SIGINT or SIGTERM...
Context canceled

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromContext added in v1.2.0

func FromContext(ctx context.Context) (signal os.Signal, ok bool)

FromContext retrieves the signal that caused a context to be canceled.

If the context was canceled by NotifyContext due to receiving a signal, FromContext returns that signal and true. Otherwise, it returns nil and false.

Example:

if sig, ok := signals.FromContext(ctx); ok {
	fmt.Printf("Context was canceled by signal: %v\n", sig)
}

func NotifyContext added in v1.1.0

func NotifyContext(
	parent context.Context,
	run func(context.Context) error,
	signals ...os.Signal,
) error

NotifyContext creates a context that is canceled when one of the specified signals is received, and returns the result of calling run with that context. The result of run is returned as is, regardless of whether it is an error.

The function takes a parent context, a function to run with the created context, and a list of signals to watch for. When one of these signals is received, the context is canceled with a Canceled error that wraps the signal.

FromContext can be used with the context to retrieve the signal that caused cancellation. context.Cause can also be used to retrieve the signal within Canceled.

func Wait

func Wait(ctx context.Context, signals ...os.Signal) os.Signal

Wait waits for the specified OS signals or context cancellation. It returns the received signal or nil if the context is canceled.

If no signals are provided, all incoming signals will be relayed. Otherwise, only the provided signals will be monitored.

Multiple calls to Wait with the same signals are allowed and will work correctly: each call will receive copies of incoming signals independently.

Types

type Canceled added in v1.2.0

type Canceled struct {
	// contains filtered or unexported fields
}

Canceled is an error that wraps context.Canceled and includes the OS signal that caused the cancellation.

It implements the error interface and provides methods to access the underlying signal and unwrap to context.Canceled.

func (Canceled) Error added in v1.2.0

func (s Canceled) Error() string

Error returns the error message, which includes the context.Canceled error and the string representation of the signal.

func (Canceled) Signal added in v1.2.0

func (s Canceled) Signal() os.Signal

Signal returns the OS signal that caused the cancellation.

func (Canceled) Unwrap added in v1.2.0

func (s Canceled) Unwrap() error

Unwrap returns the underlying context.Canceled error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL