Skip to content

Instantly share code, notes, and snippets.

@itcuihao
Last active May 17, 2023 12:04
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 itcuihao/21e8be2b293042d615b881dd8951b4c4 to your computer and use it in GitHub Desktop.
Save itcuihao/21e8be2b293042d615b881dd8951b4c4 to your computer and use it in GitHub Desktop.
golang kill self
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