Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get my Golang web server to run in the background?

I have recently completed the Wiki web development tutorial (http://golang.org/doc/articles/wiki/). I had tons of fun and I would like to experiment more with the net/http package.

However, I noticed that when I run the wiki from a console, the wiki takes over the console. If I close the console terminal or stop the process with CTRL+Z then the server stops.

How can I get the server to run in the background? I think the term for that is running in a daemon.

I'm running this on Ubuntu 12.04. Thanks for any help.

like image 736
quakkels Avatar asked Sep 18 '12 23:09

quakkels


People also ask

How to run golang in background?

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 host a Golang server?

Now let's try out this setup. Start the web server with go run server.go and visit http://localhost:8080/hello . If the server responds with "Hello!" , you can continue to the next step, where you'll learn how to add basic security to your Golang web server routes.

What is Nohup out file in Linux?

Nohup, short for no hang up is a command in Linux systems that keep processes running even after exiting the shell or terminal. Nohup prevents the processes or jobs from receiving the SIGHUP (Signal Hang UP) signal. This is a signal that is sent to a process upon closing or exiting the terminal.


1 Answers

Simple / Usable things first

If you want a start script without much effort, you could use the upstart service. See the corresponding manual page and /etc/init/*.conf for examples. After creating such a process you can start your server by calling

service myserver start 

If you want more features, like specific limitations or permission management, you could try xinetd.

Using the shell

You could start your process like this:

nohup ./myexecutable & 

The & tells the shell to start the command in the background, keeping it in the job list. On some shells, the job is killed if the parent shell exits using the HANGUP signal. To prevent this, you can launch your command using the nohup command, which discards the HANGUP signal.

However, this does not work, if the called process reconnects the HANGUP signal.

To be really sure, you need to remove the process from the shell's joblist. For two well known shells this can be achieved as follows:

bash:

./myexecutable & disown <pid> 

zsh:

./myexecutable &! 

Killing your background job

Normally, the shell prints the PID of the process, which then can be killed using the kill command, to stop the server. If your shell does not print the PID, you can get it using

echo $! 

directly after execution. This prints the PID of the forked process.

like image 191
nemo Avatar answered Sep 21 '22 13:09

nemo