Posted on September 4, 2012 by

The Problem with a Golang Daemon

[Update 11/29/2013: I ran across a repo of @VividCortex ‘s here https://github.com/VividCortex/godaemon. It’s an awesome example of how flexible Go is. VividCortex has some great tools to work with Go programs in high availability situations and you should check them out]

I’ve read a lot of requests for a daemon() call in Go. I came from C, and am used to having this function available as well. I even use daemonization in Python. There is a PEP out there and everything, but I tend to implement ActiveState’s example.

If you look around the internet, all daemon code examples seem to originate from W. Richard Stevens’ Unix Network Programming example. It’s the definitive guide. Interestingly enough, the double fork() I hear about so often is only recommended on SystemV based operating systems. It isn’t used in *BSD(at least 44BSD-Lite and FreeBSD up till today). Anyway, this code was also written in 1990. The age of his example is not important, but all the code that has been written over the years is. There are tools available that will run your program as a daemon, and monitor the status of that program.

So the problem with a Go daemon isn’t the intricacies of goroutines during package initialization, but the fact that there are better ways to run a service than a daemon() function. You should be using these tools, not worrying about trying to hack a daemon() function into your Go application.

I use Upstart. I have a config file that looks like

description "My Go Service"
author      "Ryan Day"
 
start on (local-filesystems and net-device-up)
stop on runlevel [!2345]
 
respawn
exec /home/ubuntu/gocode/mygoservice/service

I don’t have any “expect daemon” or “expect fork” here, because I’m not doing either of those things. I’m just running my application. When (yes, when) my app crashes, or an unexpected signal is sent, it will be respawned. Inside my app I have to handle SIGTERM correctly, but thats about it.

I think this is a totally valid method of running a Go application in the background. If you are using Go, you are doing something new. You don’t have to conform to any predefined processes in your company. Instead of trying to write your C application in Go, write a Go application from the ground up. Good luck!