Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I should run my Golang process in background?

This question is not strictly programming related, but for sure important for programmers.

I wrote a simple smtp server, when I run it from console all is fine, except it is blocking the command line.

I know I can run it via

nohup ... &

or via screen / tmux etc

But the question is, how should I implement my program it runs in the background and it will be a pleasure for a system administrator to set it up and manage the process ?

Some guys with far more experience than me, at golang-nuts, wrote, they don't use fork etc, and use some "wrapper" in form from monit etc.

The target platform is Debian based, all other stuff on the box are init.d based.

Any good resources for that topic or sources of a well written example project ?

like image 951
astropanic Avatar asked Jan 26 '13 12:01

astropanic


People also ask

How to run a function in background in golang?

To make a function run in the background, insert the keyword `go` before the call (like you do with `defer`). Now, the `doSomething` function will run in the background in a goroutine.

How do I run a process in the background?

Placing a Running Foreground Process into the BackgroundExecute the command to run your process. Press CTRL+Z to put the process into sleep. Run the bg command to wake the process and run it in the backround.

Which command is used to put a process in background?

The bg command is used to resume a background process. It can be used with or without a job number. If you use it without a job number the default job is brought to the foreground. The process still runs in the background.

How do you build in go?

Add the Go install directory to your system's shell path. That way, you'll be able to run your program's executable without specifying where the executable is. Once you've updated the shell path, run the go install command to compile and install the package. Run your application by simply typing its name.


1 Answers

As Nick mentioned Supervisord is a great option that has also worked well in my experience.

Nick mentioned problems with forking- forking itself works fine AFAICT. The issue is not forking but dropping privileges. Due to the way the Go runtime starts the thread pool that goroutines are multiplexed over (when GOMAXPROX > 1), the setuid systemcall is not a reliable way to drop permissions.

Instead, you should run your program as a non-privileged user and use the setcap utility to grant it the needed permissions.

For example, to allow binding to a low port number (like 80) run will need to run setcap once on the executable: sudo setcap 'cap_net_bind_service=+ep' /opt/yourGoBinary

You may need to install setcap: sudo aptitude install libcap2-bin

like image 152
voidlogic Avatar answered Nov 10 '22 01:11

voidlogic