The launch method of the Linux daemon

  • 2020-05-15 02:45:41
  • OfStack

A "daemon" (daemon) is a process that runs in the background (daemon).

1. The origin of the problem
Once the Web application is written, the next thing to do is to launch it and let it run in the background.
It's not easy. For example, here is one of the simplest Node applications, 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);

You start it at the command line.


$ node server.js

It looks like 1 slice is normal and everyone is happy to be able to access port 5000. However, once you exit the command line window, the application is no longer accessible.
How do you make it a daemon (daemon) of the system, a service (service), and a service that runs there?
2. Foreground tasks and background tasks
The script that starts like this is called the "foreground task" (foreground job). It monopolizes the command line window and can only execute other commands when it is finished running or manually aborted.
The first step in becoming a daemon is to change it to "background task" (background job).


$ node server.js &

By putting an ampersand at the end of a command, the process is called a "background task." If you want to turn a running foreground task into a background task, press ctrl + z, and then execute the bg command (let the last suspended background task continue).
Background tasks have two features.

Inherit standard output (stdout) and standard error (stderr) from the current session (dialog). Therefore, all the output of the background task is still displayed synchronously from the command line. No longer inherits the current standard input of session (stdin). You can't enter commands into this task. If it tries to read standard input, it suspends execution (halt).

As you can see, there is only one essential difference between a "background task" and a "foreground task" : whether or not standard input is inherited. Therefore, the user can enter other commands while performing background tasks.
3. SIGHUP signal
Does a process become a daemon when it becomes a "background task"? Or will the "background tasks" continue after the user exits session?
The Linux system is designed like this.

The user is ready to exit session The system sends an SIGHUP signal to the session session signals SIGHUP to all child processes When the child process receives the SIGHUP signal, it exits automatically

The process above explains why the "foreground task" exits with session's exit: it receives an SIGHUP signal.
Will the background task also receive an SIGHUP signal?
This is determined by the huponexit parameter of Shell.


$ shopt | grep huponexit

Execute the above command and you will see the value of the huponexit parameter.
On most Linux systems, this parameter is turned off by default (off). Therefore, when the session exits, it does not send the SIGHUP signal to the "background task". So, in general, "background tasks" do not exit with session 1.
4. disown command
Starting daemons with "background tasks" is not safe, as 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 task" list (the result returned by the jobs command). As long as a "background task" is not on this list, session will definitely not send an SIGHUP signal to it.


$ node server.js &
$ disown

After executing the above command, the server.js process is removed from the "background tasks" list. You can execute the jobs command to verify that there is no such process in the output.
The usage of disown is as follows.


#  Removed from the recent 1 Two background tasks that are being performed 
$ disown

#  Remove all background tasks that are being performed 
$ disown -r

#  Remove all background tasks 
$ disown -a

#  Do not remove background tasks, but make them unreachable SIGHUP signal 
$ disown -h

#  According to the jobId , remove the specified background task 
$ disown %2
$ disown -h %2

5. Standard I/O
After using the disown command, there is one more problem. That is, after exiting session, if the background process interacts with the standard I/O, it will still die.
Take the above script as an example, and now add 1 line.


var http = require('http');

http.createServer(function(req, res) {
 console.log('server starts...'); //  To join the trip 
 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 port 5000, and you will find that it is not connected.
This is because the standard I/O for "background tasks" inherits from the current session, and the disown command does not change this point. Once the "background task" read-write standard, I/O, is found to no longer exist, so an error is reported to terminate the execution.
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

This way, there is basically no problem.
6. nohup command
A more convenient command than disown is nohub.


$ nohup node server.js &

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

Block the SIGHUP signal from reaching this process. Close standard input. The process is no longer able to receive any input, even when running in the foreground. Redirect stdout and stderror to file nohup.out.

That is, the nohup command actually separates the child process from the session where it is located.
Note that the nohup command does not automatically change the process to a "background task," so you must add an ampersand.
7. Screen command and Tmux command
Another idea is to use terminal multiplexer (terminal multiplexer: manage multiple session in the same terminal), typically the Screen command and Tmux command.
They can create another session inside the current session. In this way, the current session 1 termination does not affect the other session. Also, if you log back in later, you can reconnect to the newly created session.
The usage of Screen is as follows.


$ node server.js
0

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


$ node server.js
1

If you create more than one background session, you need to specify a name for them.


$ node server.js
2

If you want to stop an session, you can cut it back and press ctrl + c and ctrl + d.
Tmux is more powerful than Screen, and its basic usage is as follows.


$ tmux
$ node server.js

#  Return to original session
$ tmux detach

In addition to tmux detach, another method is to press Ctrl + B and d to return to the original session.


$ node server.js
4

If you create more than one session, you need to specify a name for each session.


$ node server.js
5

8. Node tools
For Node applications, you don't have to use the above method. There are a number of specific startup tools: forever, nodemon, and pm2.
forever's simple function is to ensure that when a process exits, the application is automatically restarted.


$ node server.js
6

nodemon1 is only used at development time, and its greatest strength is the watch feature, which automatically restarts the process when a file changes.


$ node server.js
7

pm2 is the most powerful. In addition to restarting processes, it can also collect logs and monitor them in real time.


#  Start the application 
$ pm2 start app.js

#  Specifies how many processes are started at the same time CPU Core number determines), composition 1 A cluster 
$ pm2 start app.js -i max

#  List all tasks 
$ pm2 list

#  Stop specifying a task 
$ pm2 stop 0

 #   Restart the specified task 
$ pm2 restart 0

#  Delete the specified task 
$ pm2 delete 0

#  Save all current tasks for later recovery 
$ pm2 save

#  Lists the statistics for each process 
$ pm2 monit

#  View all logs 
$ pm2 logs

#  Export data 
$ pm2 dump

#  Restart all processes 
$ pm2 kill
$ pm2 resurect

#  Start the web interface  http://localhost:9615
$ pm2 web

10. Systemd
In addition to dedicated tools, the Linux system has its own daemon management tool, Systemd. It is a part of the operating system, directly interacting with the kernel, with excellent performance and extremely powerful functions. We can completely hand over the program to Systemd and make the system unified 1 management and become a real system service.

The above is the entire content of this article, I hope to help you with your study.


Related articles: