Daemons are processes that run in the background all the time.

This article describes how to start a Web application as a daemon.

First, the origin of the problem

Once your Web application is written, the next thing you do is start it up and keep it running in the background.

It’s not easy. For example, here is the simplest Node application server.js with only 6 lines.


var http = require('http');

http.createServer(function(req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World');
}).listen(5000);
Copy the code

You launch it from the command line.


$ node server.js
Copy the code

Everything looks fine, and everyone can happily access port 5000. However, once you exit the command line window, the application exits altogether and is no longer accessible.

How do you make it a system daemon, a service, that runs there all the time?

Second, foreground task and background task

The script that gets started like this is called “foreground job”. It monopolizes the command line window and cannot execute other commands until it is finished or terminated manually.

The first step to becoming a daemon is to change it to a background job.


$ node server.js &
Copy the code

By placing an ampersand at the end of a command, the initiated process becomes a “background task”. To change a running “foreground task” to a “background task”, press CTRL + Z and then run the bg command (to resume the most recently paused “background task”).

Background tasks have two characteristics.

  1. Inherits the standard output (STdout) and standard error (stderr) of the current session (conversation). Therefore, all output from background tasks is still displayed synchronously on the command line.
  2. No longer inherits the current session standard input (stdin). You can’t input commands into this task. If it tries to read standard input, execution is paused (HALT).

As you can see, there is only one essential difference between “background tasks” and “foreground tasks” : whether standard input is inherited. Therefore, users can enter other commands while performing background tasks.

SIGHUP signal

Does a process become a daemon when it becomes a “background task”? In other words, does the “background task” continue after the user exits the session?

This is how the Linux system is designed.

  1. The user is about to exit the session. Procedure
  2. Emitted by the system to this sessionSIGHUPsignal
  3. The session will beSIGHUPSignals are sent to all child processes
  4. Child process receivedSIGHUPAfter the signal, automatically exit

The above flow explains why the “foreground task” exits with the session exit: it receives the SIGHUP signal.

Does the “background task” also receive the SIGHUP signal?

This is determined by the Shell’s huponexit argument.


$ shopt | grep huponexit
Copy the code

Execute the command above and you will see the value of the huponExit parameter.

On most Linux systems, this parameter is off by default. Therefore, the SIGHUP signal is not sent to the “background task” when the session exits. Therefore, generally speaking, “background tasks” do not exit with the session.

Disown command

It is not safe to start “daemon” through “background task” because some systems may have the huponExit parameter turned on (on).

A safer approach is to use the disown command. It removes the specified task from the “background tasks” list (the result of the JOBS command). As long as a “background task” is not in the list, the session will definitely not send it a SIGHUP signal.


$ node server.js &
$ disown
Copy the code

After executing the above command, the server.js process is removed from the “background tasks” list. You can run the jobs command to verify that the process will not appear in the output.

Disown can be used as follows.

$disown -r # Remove all background tasks $disown -a # Do not remove background tasks But let them not receive SIGHUP signal $disown -h # according to jobId, move out of the specified background task $disown %2 $disown -h %2Copy the code

Standard I/O

After using the disown command, there is another problem. That is, after exiting the session, if a background process interacts with standard I/O, it will still hang.

Using the script above as an example, now add a line.

var http = require('http'); http.createServer(function(req, res) { console.log('server starts... '); Res.writehead (200, {' content-type ': 'text/plain'}); res.end('Hello World'); }).listen(5000);Copy the code

Start the above script and then run the disown command.


$ node server.js &
$ disown
Copy the code

Then, you exit the session, access port 5000, and you can’t connect.

This is because the standard I/O for “background tasks” inherits from the current session, and disown does not change this. Once the “background task” reads or writes standard I/O, it finds that it no longer exists, so it aborts execution with an error.

To solve this problem, the standard I/O for “background tasks” needs to be redirected.


$ node server.js > stdout.txt 2> stderr.txt < /dev/null &
$ disown
Copy the code

The above implementation, basically no problem.

Nohub command

A more convenient command than disown is nohub.


$ nohup node server.js &
Copy the code

The nohup command does three things for the server.js process.

  • stopSIGHUPSignals are sent to this process.
  • Turn off standard input. The process can no longer accept any input, even when running in the foreground.
  • Redirects standard output and standard error to filesnohup.out.

That is, the nohup command effectively separates the child process from its session.

Note that the nohup command does not automatically turn a process into a “background task”, so an ampersand must be added.

Screen command and Tmux command

The other way of thinking about it is to use terminal multiplexer, typically Screen and Tmux.

They can create another session within the current session. In this way, the termination of the current session does not affect other sessions. In addition, if you log in again later, you can also connect to the session created earlier.

The uses of Screen are as follows.

Create a session $screen $node server.jsCopy the code

Then, press CTRL + A and CTRL + D to return to the original session and log out from there. The next time you log in, cut back.


$ screen -r
Copy the code

If you create multiple background sessions, you need to name them.

$screen -S name $screen -r name $screen -r pid_numberCopy the code

To stop a session, cut it back and press CTRL + C and CTRL + D.

Tmux is more powerful than Screen, and its basic uses are as follows.

$tmux $node server.js # returns the original session $tmux detachCopy the code

In addition to TMUx detach, another way is to press Ctrl + B and D to return to the original session.

Session $tmux ATTACH is running in the backgroundCopy the code

If you create multiple sessions, you need to specify a name for each session.

# add session $tmux new -s session_name # add session $tmux new -s session_name # Add session $tmux $tmux detach # Kill specified session $tmux kill -session-t session-nameCopy the code

Node tool

Instead of using this method, there are several tools for starting Node applications: Forever, Nodemon, and PM2.

Forever simply ensures that the app restarts automatically when a process exits.

$forever Start app.js # Stop the server process $forever Stop Id # Restart the server process $forever restart $forever-w server.js # -m specifies the maximum number of times to restart the server. $forever-m 5 server.js # Lists all processesCopy the code

Nodemon is generally used only for development purposes, but its greatest strength is its Watch function, which automatically restarts the process once a file changes.

$nodemon --watch app --watch libs server.jsCopy the code

The PM2 provides the most powerful functions. In addition to restarting processes, it can also collect logs and monitor processes in real time.

$pm2 start app.js $pm2 start app.js -i Max # List all tasks $pm2 list # Stop task $pm2 stop 0 # Restart task $pm2 restart 0 # Delete task $pm2 Delete 0 # save all current tasks, $pm2 dump $pm2 dump $pm2 kill $pm2 resurect # Start the web UI http://localhost:9615 $pm2 WebCopy the code

Ten, Systemd

In addition to proprietary tools, Linux has its own daemon management tool, Systemd. It is the part of the operating system that interacts directly with the kernel, with excellent performance and extremely powerful functions. We can completely give the program to Systemd, so that the system unified management, become a real sense of the system service.

In the next article, I’ll introduce Systemd.

(after)