Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active December 17, 2019 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsscoder/687ea9c673b8965ae14cb65a900c8180 to your computer and use it in GitHub Desktop.
Save gsscoder/687ea9c673b8965ae14cb65a900c8180 to your computer and use it in GitHub Desktop.
Go goroutine and channel to monitor process end
// compile: go build -o alive
// usage:
// $ ps -A | rg firefox
// 35761 ?? 0:23.28 /Applications/Firefox.app/Contents/MacOS/firefox
// ./alive 35761
package main
import (
"fmt"
"github.com/shirou/gopsutil/process"
"os"
"strconv"
"time"
)
func die(message string) {
fmt.Println(message)
os.Exit(1)
}
func main() {
if len(os.Args) != 2 {
die("PID missing")
}
pid, err := strconv.Atoi(os.Args[1])
if err != nil {
die("Bad PID")
}
fmt.Printf("Monitoring %d ...\n", pid)
// channel 'c' is used to wait for goroutine end
c := make(chan struct{})
go func() {
for {
alive, err := process.PidExists(int32(pid))
if err != nil {
fmt.Print("ERROR ")
} else if err == nil && !alive {
fmt.Printf("%d died :(\n", pid)
// we've done
c <- struct{}{}
}
time.Sleep(time.Second)
}
}()
<-c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment