Golang捕获信号

扫码查看
本文介绍了Golang捕获信号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Go中实现一个流程包装器。基本上它会做什么,是启动一个进程(可以说一个节点服务器)并监控它(捕获像SIGKILL,SIGTERM等信号)。

我想方式要做的是使用 syscall.Exec 来启动节点服务器:

  func launchCmd(path string,args [] string){
err:= syscall.Exec(path,args,os.Environ())
if err!= nil {
恐慌(错误)
}
}

然后我想捕获由 syscall 执行的命令生成的所有可能信号。

解决方案

Go有三种执行程序的方法:


  1. 系统调用 package with ,,

  2. os 使用

  3. os / exec 包含

属于低级别。它返回一个 uintptr 作为句柄。



os.StartProcess 给你一个很好的 os.Process 结构,你可以调用。 os / exec 使您可以在管道上使用 io.ReaderWriter 。内部使用 syscall



读取 似乎有点棘手。如果可能的话, syscall 就可以做到。我没有看到任何明显的更高级别的软件包。



要接收信号,您可以使用像这样:

  sigc:= make(chan os.Signal,1)
signal.Notify(sigc,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT )
去func(){
s:=< -sigc
// ...做某事...
}()

您只需更改您有兴趣收听的信号即可。如果您没有指定信号,它会捕获所有可以捕获的信号。



您可以使用或来映射信号。你可以从 Process.Pid 获得pid,或者从。


I want to implement a "process wrapper" in Go. Basically what it will do, is launch a process (lets say a node server) and monitor it (catch signals like SIGKILL, SIGTERM ...)

I think the way to do is to launch the node server in a go routine using syscall.Exec:

func launchCmd(path string, args []string) {
  err := syscall.Exec(path, args, os.Environ())
  if err != nil {
    panic(err)
  }
}

Then I'd like to catch every possible signals generated by the command executed by syscall. I'm pretty new to Go, any help would be appreciated.

解决方案

There are three ways of executing a program in Go:

  1. syscall package with syscall.Exec, syscall.ForkExec, syscall.StartProcess
  2. os package with os.StartProcess
  3. os/exec package with exec.Command

syscall.StartProcess is low level. It returns a uintptr as a handle.

os.StartProcess gives you a nice os.Process struct that you can call Signal on. os/exec gives you io.ReaderWriter to use on a pipe. Both use syscall internally.

Reading signals sent from a process other than your own seems a bit tricky. If it was possible, syscall would be able to do it. I don't see anything obvious in the higher level packages.

To receive a signal you can use signal.Notify like this:

sigc := make(chan os.Signal, 1)
signal.Notify(sigc,
    syscall.SIGHUP,
    syscall.SIGINT,
    syscall.SIGTERM,
    syscall.SIGQUIT)
go func() {
    s := <-sigc
    // ... do something ...
}()

You just need to change the signals you're interested in listening to. If you don't specify a signal, it'll catch all the signals that can be captured.

You would use syscall.Kill or Process.Signal to map the signal. You can get the pid from Process.Pid or as a result from syscall.StartProcess.

这篇关于Golang捕获信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 14:45
查看更多