如何使用Go正确启动一个将进行守护化的进程?

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

How to properly start a process that will daemonize using Go?

问题

我写了一个Go程序,它会运行另一个Go程序来进行守护进程。

我想知道第一个程序在子进程进行守护化之前需要等待多长时间。

cmd := exec.Command(path1)
cmd.Start()
// 在这里退出

或者

cmd := exec.Command(path1)
cmd.Run()
// 在这里退出

或者

cmd := exec.Command(path1)
cmd.Start()
time.Sleep(5 * time.Second)
// 在这里退出

如果我使用cmd.Run(),在启动的守护程序中哪个命令/操作将结束第一个程序中的"等待"状态。

英文:

I write Go program that will run another Go program that will daemonize.

I am wondering how much time the first program must wait before its child process is daemonising.

cmd := exec.Command(path1)
cmd.Start()
    // exit here

or

cmd := exec.Command(path1)
cmd.Run()
    // exit here

or

cmd := exec.Command(path1)
cmd.Start()
time.Sleep(5 * time.Second)
    // exit here

If I use cmd.Run() what command/action in started daemon program will end "waiting" in first program.

答案1

得分: 3

守护进程化一个进程只是一个将进程分叉的花哨方式。这意味着你启动的进程将在守护进程启动后立即退出。因此,你应该使用Run,它会等待启动的进程返回(成功分叉)。

如果你想等待守护进程的状态,最可靠的方法是由守护进程发出信号。例如,使用套接字、文件或共享内存。

英文:

Daemonizing a process is just a fancy way of forking the process. That means that the process you start will exit as soon as the daemonized process is started. Therefore you want to use Run, which will wait for the started process to return (the successful fork).

<!-- language: lang-none -->

Process A:
|
|`-- run(B)
|    Process B:
|    |
|    |`-- daemonize(C)
|    |
|     `-- exit
|
 `-- daemonizing done

If you want to wait for a state of the daemon, the most reliable way is to be signalled by the daemon. For example using a socket, a file or shared memory.

huangapple
  • 本文由 发表于 2014年4月10日 07:57:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/22976134.html
匿名

发表评论

匿名网友

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

确定