Skip to content

Instantly share code, notes, and snippets.

@djoreilly
Last active August 26, 2021 16:01
Show Gist options
  • Save djoreilly/f82c2f29bb0dc501f6b957d705037404 to your computer and use it in GitHub Desktop.
Save djoreilly/f82c2f29bb0dc501f6b957d705037404 to your computer and use it in GitHub Desktop.

Revisions

  1. djoreilly revised this gist Aug 26, 2021. No changes.
  2. djoreilly created this gist Aug 26, 2021.
    43 changes: 43 additions & 0 deletions interrupted.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    package main

    import (
    "fmt"
    "os"
    "os/exec"
    "os/signal"
    "syscall"
    "time"
    )

    func interrupted(sigCh <-chan os.Signal) bool {
    // non-blocking read on channel
    select {
    case <-sigCh:
    default:
    return false // channel is empty
    }
    return true
    }

    func main() {
    sigCh := make(chan os.Signal, 1)
    signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)

    fmt.Println("about to sleep")
    startTime := time.Now()

    cmd := exec.Command("sleep", "5")
    // prevent the shell from signalling children https://stackoverflow.com/a/33171307
    cmd.SysProcAttr = &syscall.SysProcAttr{
    Setpgid: true,
    }
    cmd.Run()

    fmt.Printf("slept for %0.0f sec\n", time.Now().Sub(startTime).Seconds())

    if interrupted(sigCh) {
    fmt.Println("interrupted")
    } else {
    fmt.Println("not interrupted")
    }
    }
    10 changes: 10 additions & 0 deletions run
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    $ go run interrupted.go
    about to sleep
    ^C^C^C
    slept for 5 sec
    interrupted

    $ go run interrupted.go
    about to sleep
    slept for 5 sec
    not interrupted