Reference:http://www.ruanyifeng.com/blog/2016/02/linux-daemon.html
The 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(reqRes){Res.Writehead (200{ ' Content-type ' : ' Text/plain ' }) . (}) .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.
| 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.
# 移出最近一个正在执行的后台任务$ disown# 移出所有正在执行的后台任务$ disown -r# 移出所有后台任务$ disown -a# 不移出后台任务,但是让它们不会收到SIGHUP信号$ disown -h# 根据jobId,移出指定的后台任务$ 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(reqRes){Console.Log(' Server starts ... ');Join this row res.Writehead (200{ ' Content-type ' : ' Text/plain ' }) . (}) .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.
# 新建一个 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.
-r
If you create more than one background session, you need to specify a name for them.
-S name# 切回指定 session$ screen -r name$ screen -r pid_number# 列出所有 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# 返回原来的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.
# 下次登录时,返回后台正在运行服务session$ tmux attach
If you create more than one session, you need to specify a name for each session.
# 新建 session$ tmux new -s session_name# 切换到指定 session$ tmux attach -t session_name# 列出所有 session$ tmux list-sessions# 退出当前 session,返回前一个 session $ tmux detach# 杀死指定 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.
# 作为前台任务启动$ forever server.js# 作为服务进程启动 $ forever start app.js# 停止服务进程$ forever stop Id# 重启服务进程$ forever restart Id# 监视当前目录的文件变动,一有变动就重启$ forever -w server.js# -m 参数指定最多重启次数$ forever -m 5 server.js # 列出所有进程$ forever list
nodemon
Generally only used in development, its greatest advantage is the watch function, once the file changes, automatically restart the process.
# 默认监视当前目录的文件变化$ nodemon server.js# 监视指定文件的变化 $ 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# specify how many processes (determined by the number of CPU cores) to compose a cluster $ PM2 start App.js -i max# list all Tasks $ pm2 List# stop specifying task $ PM2 Stop 0# restart specified task $ pm2 restart 0# delete the specified task $ pm2 delete 0# save all current tasks, Can later recover $ pm2 save# list statistics for each process $ PM2 monit# view all logs $ pm2 logs< Span class= "token comment" ># 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.
Finish
[Linux] How to start the Linux daemon