Last active
December 17, 2019 05:19
-
-
Save gsscoder/687ea9c673b8965ae14cb65a900c8180 to your computer and use it in GitHub Desktop.
Go goroutine and channel to monitor process end
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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