3

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.

kostix
  • 51,517
  • 14
  • 93
  • 176
Artem
  • 1,307
  • 2
  • 11
  • 23

1 Answers1

3

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).

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.

nemo
  • 55,207
  • 13
  • 135
  • 135
  • Does `exec` in my case replace `fork` in common daemonizing examples? or started program B must still `fork` and `setsid` or only `setsid` is enough. As I understand `exec.Command(x).Run()` is `fork exec` and second `fork` is not required. – Artem Apr 10 '14 at 07:40
  • The call to `setsid` is obligatory to entangle the new process from it's previous [process group](http://stackoverflow.com/questions/6548823/use-and-meaning-of-session-and-process-group-in-unix). However, if you're having trouble understanding daemonization or forking, I would recommend asking a new question instead of discussing it here. – nemo Apr 10 '14 at 12:02