Last active
May 17, 2023 12:04
-
-
Save itcuihao/21e8be2b293042d615b881dd8951b4c4 to your computer and use it in GitHub Desktop.
golang kill self
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
package main | |
import ( | |
"fmt" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
func main() { | |
// 创建一个信号通道 | |
sigChan := make(chan os.Signal, 1) | |
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) | |
// 启动一个goroutine等待信号 | |
go func() { | |
sig := <-sigChan | |
fmt.Printf("received signal %v, shutting down...\n", sig) | |
// 1秒后给自己发送os.Interrupt信号 | |
time.AfterFunc(time.Second, func() { | |
pid := os.Getpid() | |
proc, err := os.FindProcess(pid) | |
if err != nil { | |
fmt.Printf("failed to find process %d: %v\n", pid, err) | |
return | |
} | |
err = proc.Signal(os.Interrupt) | |
if err != nil { | |
fmt.Printf("failed to send signal %v to process %d: %v\n", os.Interrupt, pid, err) | |
} | |
}) | |
}() | |
// 模拟程序运行 | |
for { | |
fmt.Println("running...") | |
time.Sleep(time.Second) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment