Daemon (daemon) is the process that is running in the background (daemon).
This article describes how to start a Web app as a daemon.
First, the origin of the problem
After the Web application is written, the next thing to do is to start it and keep it running in the background.
It's not easy. For example, here is one of the simplest node apps server.js
, with only 6 rows.
var http = require (' http '); Http.createserver (function (req, res) { Res.writehead ($, {' Content-type ': ' Text/plain '}); Res.end (' Hello world '). Listen (5000);
You start it under the command line.
$ node Server.js
Everything looks normal and everyone is happy to access Port 5000. However, once you exit the command-line window, the app exits with no access.
How do you make it a system daemon (daemon) that becomes a service that runs all the time?
Second, the foreground task and the background task
The script that starts up like this is called a "foreground task" (foreground job). It will monopolize the command-line window and can execute other commands only if it is run out or manually aborted.
The first step in becoming a daemon is to change it to a "background task" (Background job).
$ node Server.js &
As long as you add a symbol at the end of the command &
, the started process becomes a "background task." If you want a running foreground task to become a background task, you can press ctrl + z
and then execute the bg
command (let the most recent paused background task continue).
"Background Tasks" has two features.
- Inherits the standard output (STDOUT) and standard error (STDERR) of the current session (Dialog). Therefore, all the output from the background task is still displayed synchronously at the command line.
- No longer inherits the standard input (stdin) of the current session. You cannot enter a command into this task. If it tries to read the standard input, it pauses execution (halt).
As you can see, the essential difference between "background tasks" and "foreground tasks" is only one: whether to inherit standard input. Therefore, the user can also enter additional commands while performing background tasks.
Three, Sighup signal
becomes a "background task", does a process become a daemon? Or, after the user exits the session, will "background tasks" continue to execute?
The Linux system is designed like this.
- User ready to exit session
- The system sends a signal to the session
SIGHUP
- Session sends the
SIGHUP
signal to all child processes
SIGHUP
automatically exits when a child process receives a signal
The process above explains why the "foreground task" exits as the session exits: because it receives a SIGHUP
signal.
So will "background tasks" also receive a SIGHUP
signal?
This is determined by the Shell's huponexit
parameters.
$ shopt | grep huponexit
Execute the above command and you will see huponexit
the value of the parameter.
Most Linux systems, this parameter is turned off by default ( off
). Therefore, when the session exits, the signal is not SIGHUP
sent to the "background task". So, in general, "background tasks" do not exit with the session.
Iv. Disown command
It is not safe to start the daemon through the background task because some of the system huponexit
parameters may be open ( on
).
A more insured approach is to use disown
commands. It removes the specified task from the Background Tasks list ( jobs
The return result of the command). A "background task" as long as it is not in this list, the session will definitely not SIGHUP
signal it.
$ node Server.js &$ Disown
After executing the above command, the server.js
process is moved out of the background tasks list. You can perform jobs
command validation, and the output will not have this process.
disown
Use the following.
# move out of a recently executing background task $ disown# move out all the background tasks that are being performed $ disown-r# Remove all background tasks $ disown-a# do not move out of the background task, but let them not receive SIGHUP signal $ disown-h# According to Jobid, move out Specified background task $ disown%2$ disown-h%2
V, standard I/O
disown
after using the command, there is another problem. That is, after exiting the session, if the background process interacts with standard I/O, it will still hang.
As an example of the above script, join a row now.
var http = require (' http '); Http.createserver (function (req, res) { console.log (' server starts ... ');//Join this line Res.writehead ($, {' Content-type ': ' Text/plain '}); Res.end (' Hello world '). Listen (5000);
Start the above script, and then execute the disown
command.
$ node Server.js &$ Disown
Then, when you exit the session and access Port 5000, you will find that you are not connected.
This is because the standard I/O for "background tasks" inherits from the current session, disown
and the command does not change this. Once the "background task" reads and writes the standard I/O, it will find that it no longer exists, so the error terminates execution.
To solve this problem, you need to redirect the standard I/O for "background tasks".
$ node server.js > stdout.txt 2> stderr.txt </dev/null &$ Disown
The above implementation, basically there is no problem.
Vi. nohup Command
There are disown
more convenient orders, that is nohup
.
$ nohup Node Server.js &
nohup
The command server.js
did three things to the process.
- Prevents
SIGHUP
the signal from being sent to this process.
- Turn off standard input. The process is no longer able to receive any input, even if it is running in the foreground.
- REDIRECT standard output and standard error to file
nohup.out
.
In other words, the nohup
command actually separates the child process from the session it is in.
Note that the nohup
command does not automatically turn the process into a "background task", so you must add a &
symbol.
Seven, screen command and Tmux command
Another idea is to use the terminal multiplexer (Terminal multiplexer: Managing multiple sessions in the same terminal), typically the screen command and the Tmux command.
They can create another session in the current session. In this case, the current session once finished, does not affect the other session. You can also connect to the previously created session by re-logging in later.
The use of screen is as follows.
# Create a new session$ screen$ node server.js
Then, press ctrl + A
and ctrl + D
, go back to the original session, and exit the login from there. Next time you log in, cut back.
$ screen-r
If you create more than one background session, you need to specify a name for them.
$ screen-s name# cut back specify session$ screen-r name$ screen-r pid_number# list all session$ Screen-ls
If you want to stop a session, you can first cut it back and then press ctrl + c
and ctrl + d
.
Tmux is more powerful than screen, and its basic usage is as follows.
$ tmux$ Node server.js# back to the original session$ Tmux detach
In addition tmux detach
, the other way is to Ctrl + B
press and d
, can also go back to the original session.
# The next time you log on, return to the background running service session$ Tmux attach
If you create more than one session, you need to specify a name for each session.
# new session$ tmux new-s session_name# switch to specify session$ tmux attach-t session_name# list all session$ tmux list-sessions# exit current Session, return the previous session $ Tmux detach# kill the specified session$ tmux kill-session-t session-name
Eight, Node tool
For the Node application, you can use the above method, there are some tools specifically for launching: Forever,nodemon and PM2.
The Forever function is simple enough to ensure that the application restarts automatically when the process exits.
# as a foreground task start $ forever server.js# as a service process start $ forever start app.js# stop service process $ forever Stop id# Restart service process $ Forever Restart id# Monitor current target A change in the recorded file. Restart $ forever-w server.js#-m parameter specifies a maximum number of restarts $ forever-m 5 server.js # List all processes $ forever list
nodemon
Generally only used in development, its greatest advantage is the watch function, once the file changes, automatically restart the process.
# Default monitor current directory file changes $ nodemon server.js# monitor specified file changes $ nodemon--watch app--watch Libs server.js
The PM2 is the most powerful, with the ability to collect logs and monitor in real time, in addition to restarting the process.
# Start app $ pm2 start app.js# Specifies how many processes (determined by the number of CPU cores) to make up a cluster $ PM2 start app.js-i max# List All Tasks $ PM2 list# stop specifying tasks $ PM2 Stop 0# restart refers to Fixed task $ pm2 Restart 0# Delete specified task $ pm2 Delete 0# Save all current tasks, later can recover $ PM2 save# list statistics for each process $ PM2 monit# View all logs $ PM2 logs# Export Data $ pm2 dump# Restart all processes $ pm2 kill$ pm2 resurect# Start Web interface http://localhost:9615$ PM2 Web
Ten, Systemd
In addition to specialized tools, Linux systems have their own daemon management tools SYSTEMD. It is part of the operating system, interacting directly with the kernel, with excellent performance and extremely powerful functionality. We can completely give the program to SYSTEMD, let the system unified management, become a real system service.
In the next article, I'll introduce Systemd.
How to start the Linux daemon