The daemon (daemon) is the process that is running in the background (daemon).
First, the origin of the problem
once the Web application is written, the next thing is to start and keep it running in the background.
It's not easy. For example, the following is one of the simplest node application server.js, with only 6 lines.
var http = require (' http ');
Http.createserver (function (req, res) {
res.writehead ({' Content-type ': ' Text/plain '});
Res.end (' Hello World ');
Listen (5000);
You start it at the command line.
Everything seemed normal and everyone was happy to access Port 5000. However, once you exit the command line window, the application exits together and cannot be accessed.
How can it become a system daemon (daemon) and become a service that has been running there?
second, the foreground task and backstage task
The script that starts up like this is called a "foreground task" (foreground job). It is exclusive to the command line window and can execute other commands only if it is running out or manually aborted.
The first step to becoming a daemon is to change it to a "background task" (Background job).
As long as you add symbols to the end of the command, the started process becomes a "background task." If you want to change the foreground task that is running to a background task, you can press CTRL + Z first, and then perform the BG command (let the last paused background task continue).
"Background task" has two features .
- Inherits the standard output (STDOUT) and standard error (STDERR) of the current session (Dialog). Therefore, all output from the background task will still be displayed synchronously at the command line.
- Standard input (stdin) for the current session is no longer inherited. You cannot enter instructions for this task. If it attempts to read standard input, it suspends execution (halt).
As you can see, the essential difference between "background task" and "foreground task" is one: whether to inherit standard input. Therefore, the user can also enter other commands while performing background tasks.
third, Sighup signal
Does a process become a daemon after it becomes a "background task"? Or, after the user exits the session, does the background task continue to execute?
This is how the Linux system is designed.
- User prepares to exit session
- The system emits a SIGHUP signal to the session
- Session sends Sighup signal to all child processes
- The child process automatically exits after receiving the SIGHUP signal
The above process explains why the "foreground task" exits as the session quits: it receives a sighup signal.
So, does "background task" also receive SIGHUP signal?
This is determined by the huponexit parameters of the Shell.
If you execute the above command, you will see the value of the Huponexit parameter.
Most Linux systems, this parameter is closed by default (off). Therefore, when the session exits, the SIGHUP signal will not be sent to the "background task." Therefore, in general, background tasks do not exit with the session.
Iv. Disown Order
starting daemon with background tasks is not insured, because the huponexit parameters of some systems may be open (on).
A more insurance method is to use the disown command. It can remove the specified task from the Background Tasks list (The return result of the jobs command). A "background task" as long as it is not in this list, the session will certainly not send it a sighup signal.
$ node Server.js &
$ disown
After executing the above command, the server.js process is moved out of the background tasks list. You can perform the jobs command verification, the output will not have this process.
The use of disown is as follows.
# move out of the last background task in progress
$ disown
# Remove all background tasks in progress
$ disown-r
# Remove all background tasks
$ disown-a
# do not move out of background tasks, But let them not receive the SIGHUP signal
$ disown-h
# According to Jobid, remove the specified background task
$ disown%2
$ disown-h%2
Five, standard I/O
After using the disown command, there is another problem. That is, after exiting the session, if the background process interacts with standard I/O, it will still be dead.
As an example of the above script, join a line now.
var http = require (' http ');
Http.createserver (function (req, res) {
console.log (' server starts ... ');//Join this row
Res.writehead (200, {' Content-type ': ' Text/plain '});
Res.end (' Hello World ');
Listen (5000);
Start the script above, and then execute the disown command.
$ node Server.js &
$ disown
Then, you exit session, Access 5000 port, you will find not even.
This is because the standard I/O inheritance of "background tasks" does not change this from the current Session,disown command. Once the "background task" read and write standard I/O, you will find that it is no longer exist, so the error is terminated execution.
To solve this problem, you need to redirect the standard I/O for the background task.
$ node server.js > stdout.txt 2> stderr.txt </dev/null &
$ disown
The above implementation, basically there is no problem.
Vi. nohup Order
There are more convenient orders than disown, that is, Nohub.
The Nohup command has done three things to the server.js process.
- Prevent sighup signals 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 subprocess from the session in which it resides.
Note that the Nohup command does not automatically turn a process into a "background task", so you must add the & symbol.
Seven, screen command and Tmux command
Another idea is to use the terminal multiplexer (Terminal multiplexer: In the same terminal, manage multiple sessions), typically screen commands and Tmux commands.
They can create another session in the current session. In this case, the current session ends without affecting the other sessions. Also, you can connect to the previously created session again after you log on again.
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 previous session, and exit the login from there. Next time you log in, cut back again.
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 sessions
$ 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
# returns the original session
$ tmux Detach
In addition to Tmux detach, another method is to press CTRL + B and D, or you can go back to the previous session.
# The next time you log on, return to the background running service session
$ tmux Attach
If you create multiple sessions, you need to specify a name for each session.
# New Session
$ tmux new-s session_name
# Switch to the specified session
$ tmux attach-t session_name
# list all session
$ Tmux list-sessions
# Exit current session, return previous session
$ tmux Detach
# Kill specified session
$ tmux Kill-sessio N-t Session-name
Eight, Node tool
For Node applications, there are a number of tools that are specifically used to start up: Forever,nodemon and PM2, without the above methods.
Forever's function is very simple, is to ensure that the process exits, the application will automatically restart.
# started as a foreground task
$ forever Server.js
# started as service process
$ forever start app.js
# Stop service process
$ forever Stop Id # restart
Service Process
$ Forever Restart Id
# Monitor file changes for current directory, restart
$ forever-w server.js
#-m parameter specify maximum number of reboots
$ forever-m 5 Server.js
# List all processes
$ forever List
Nodemon is generally only used in development, its biggest advantage is watch function, once the file changes, automatically restart the process.
# Default monitoring of file changes for current directory
$ nodemon server.js
# Monitor changes to specified file
$ nodemon--watch app--watch Libs server.js
PM2 is the most powerful, in addition to restarting the process, can also be real-time collection of logs and monitoring.
# Start Application
$ pm2 start app.js
# Specifies how many processes (determined by the CPU core) should be in the same time, consisting of a cluster
$ pm2 start app.js-i Max
# list All Tasks
$ PM2 List
# Stop specifying tasks
$ pm2 Stop 0
# Restart the specified task
$ pm2 Restart 0
# Delete the specified task
$ pm2 Delete 0
# Save all current tasks, and you can restore c13/>$ pm2 Save
# List statistics for each process
$ pm2 monit
# View all logs
$ PM2 Logs
# Export data
$ PM2 Dump # reboot
all in Cheng
$ pm2 kill
$ pm2 resurect
# Launch 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 capabilities. We can completely put the program to SYSTEMD, let the system unified management, become a real sense of the system services.
The above is the entire content of this article, I hope to help you learn.