diff --git a/4-graceful-sigint/4-graceful-sigint b/4-graceful-sigint/4-graceful-sigint new file mode 100755 index 0000000..88e7917 Binary files /dev/null and b/4-graceful-sigint/4-graceful-sigint differ diff --git a/4-graceful-sigint/main.go b/4-graceful-sigint/main.go index 38c7d3d..7ab242d 100644 --- a/4-graceful-sigint/main.go +++ b/4-graceful-sigint/main.go @@ -13,10 +13,54 @@ package main -func main() { +import ( + "os" + "os/signal" + "syscall" +) + +func solution1() { // Create a process proc := MockProcess{} + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGINT) + + // Run the process (blocking) + go proc.Run() + <-sig + + done := make(chan bool, 1) + go func() { + proc.Stop() + done <- true + }() + + select { + case <-done: + return + case <-sig: + return + } +} + +func solution2() { + // Create a process + proc := MockProcess{} + + go func() { + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt) + <-c + signal.Reset() // reset interrupt handler and get back to standard behaviour : killing the process + proc.Stop() + }() + // Run the process (blocking) proc.Run() } + +func main() { + solution1() + solution2() // must run after Solution1 because the 2nd SIGINT will be fatal +}