golang exec a command on a running binary / process

huangapple go评论87阅读模式
英文:

golang exec a command on a running binary / process

问题

如果你看一下Nginx,它调用"nginx reload"来重新加载自身。有没有办法从命令行向正在运行的进程发送信号?即使主进程启动子进程,我如何向主进程发送命令以通知其子进程?

例如:

myapp start -debug // 启动服务器
myapp reload -gracefull // 优雅地停止应用程序

现在我需要发送操作系统信号来通知我的服务器执行优雅的关闭

kill -QUIT pid
kill -USR2 pid

希望我的问题足够清楚
谢谢

英文:

If you look at Nginx it calls "nginx reload" to reload itself. Is there any way to send a signal from the command line to a running process? Even if the main process starts child processes how can I send commands to the main to notify its children?

ex:

myapp start -debug // starts a server
myapp reload -gracefull // stops the app gracefully

Now i need to send os signals to notify my server to perform a graceful shutdown

kill -QUIT pid
kill -USR2 pid

I hope my question is clear enough
Thnx

答案1

得分: 7

接收信号

看一下os/signal包。

包signal实现对传入信号的访问。

文档中甚至有一个示例

// 设置用于发送信号通知的通道。
// 我们必须使用带缓冲的通道,否则在发送信号时,如果我们还没有准备好接收,就有可能错过信号。
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)

// 阻塞直到接收到信号。
s := <-c
fmt.Println("收到信号:", s)

发送信号

要了解如何发送信号,请查看signal_test.go,它使用了syscall。例如:

// 向该进程发送SIGHUP信号
t.Logf("sighup...")
syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
waitSig(t, c, syscall.SIGHUP)
英文:

Receive signals

Take a look at the os/signal package.

> Package signal implements access to incoming signals.

There is even an example in the documentation :

// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we&#39;re not ready to receive when the signal is sent.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, os.Kill)

// Block until a signal is received.
s := &lt;-c
fmt.Println(&quot;Got signal:&quot;, s)

Send signals

To see how to send signals take a look at signal_test.go, it uses syscall. For example :

// Send this process a SIGHUP
t.Logf(&quot;sighup...&quot;)
syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
waitSig(t, c, syscall.SIGHUP)

答案2

得分: 0

我发现在Go语言中,我们可以将环境变量传递给syscall.Exec函数。

err := syscall.Exec(argv0, os.Args, os.Environ())

这段代码会将当前环境变量复制到子进程中。

英文:

I figured out that in go i we can pass the environment to syscall.Exec

err := syscall.Exec(argv0. os.Args. os.Environ())

simply copies the current env to the child process.

huangapple
  • 本文由 发表于 2014年9月18日 01:11:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/25896520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定