signal

package
v0.0.0-...-184bb4f Latest Latest
Warning

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

Go to latest
Published: Jun 14, 2023 License: MIT Imports: 6 Imported by: 0

README

What Is It ?

Utility package to be used in tandem with runner package.

Used in gracefully shutdown multiple components that should not know each other, by listening system signals.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Closed

func Closed(ctx context.Context) (os.Signal, error)

Closed gets the signal that closed a context channel.

Example
package main

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

	"github.com/badu/wg-cc/pkg/signal"
)

func main() {
	ctx, cancel := signal.WithSignals(context.Background(), syscall.SIGHUP)
	defer cancel()

	// Remove this Go routine to test manually with kill -HUP PID.
	go func() {
		p, _ := os.FindProcess(os.Getpid()) // always check your errors!
		_ = p.Signal(syscall.SIGHUP)        // don't ignore errors!
	}()

	<-ctx.Done()

	sig, err := signal.Closed(ctx)

	if err != nil {
		_, _ = fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	fmt.Println(sig)
}
Output:

hangup

func WithSignals

func WithSignals(parent context.Context, signals ...os.Signal) (context.Context, context.CancelFunc)

WithSignals returns a copy of the parent context cancelable by the given system signals. The signals are reset when the context's Done channel is closed.

Example
package main

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

	"github.com/badu/wg-cc/pkg/signal"
)

func main() {
	ctx, cancel := signal.WithSignals(context.Background(), syscall.SIGUSR2)
	defer cancel()

	// Remove this Go routine to test manually with kill -USR2 PID.
	go func() {
		p, _ := os.FindProcess(os.Getpid()) // always check your errors!
		_ = p.Signal(syscall.SIGUSR2)       // don't ignore errors!
	}()

	<-ctx.Done()
	fmt.Println("Signaled!")
}
Output:

Signaled!

func WithTermination

func WithTermination(ctx context.Context) (context.Context, context.CancelFunc)

WithTermination creates a context canceled on signals SIGINT or SIGTERM.

Example
package main

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

	"github.com/badu/wg-cc/pkg/signal"
)

func main() {
	ctx, cancel := signal.WithTermination(context.Background())
	defer cancel()

	// Remove this Go routine to test manually.
	go func() {
		p, _ := os.FindProcess(os.Getpid()) // always check your errors!
		_ = p.Signal(syscall.SIGINT)        // don't ignore errors!
	}()

	<-ctx.Done()
	fmt.Println("Interrupted!")
}
Output:

Interrupted!

Types

This section is empty.

Jump to

Keyboard shortcuts

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