How to start the Linux daemon

Source: Internet
Author: User
Tags node server

Guide "Daemon" (daemon) is a process that is running in the background (daemon), usually starts with the daemon at the start of the system, this article describes how to start a Web application as a daemon.

first, the origin of the problem

After the Web application is written, the next thing to do is to start and keep it running in the background, which is not easy, for example, here is the simplest node app, 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, everyone can happily access Port 5000, but once you exit the command-line window, the app exits, it can't be accessed, how can it become a daemon (daemon), a service, where it's been running?

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, only run out or manually abort, in order to execute other commands, become the first step of the daemon, is to change it to "background task" (Background job).

$ node Server.js &

As long as the symbol & is added 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 first, and then execute the BG command (let the most recent paused background task continue).
"Background Tasks" has two features.

1. Inherit 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.

2. 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.

1. The user is ready to exit the session
2. The system sends a SIGHUP signal to the session
3.session send sighup signal to all child processes
4. The child process automatically exits after receiving the SIGHUP 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 sighup signals?
This is determined by the shell's huponexit parameter.

$ shopt | grep huponexit

Execute the above command and you will see the value of the Huponexit parameter.
Most Linux systems, this parameter is off by default (off). Therefore, when the session exits, the SIGHUP signal is not 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's Huponexit parameters may be open (on).
A more insured approach is to use the disown command. It removes 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 a sighup signal to it.

$ node Server.js &$ Disown

After executing the above command, the server.js process is moved out of 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.

# 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

There is a problem after using the disown command. 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 inheritance of "background tasks" from the current Session,disown command does not change this. Once the "background task" reads and writes standard I/O, it will find that it is no longer present, so the error terminates execution, in order to resolve this problem, the "background task" of the standard I/O is redirected.

$ node server.js > stdout.txt 2> stderr.txt </dev/null &$ Disown

The above implementation, basically there is no problem.

vi. nohup Command

There are more convenient commands than disown, that is nohup.

$ nohup Node Server.js &

The Nohup command did three things for the server.js process.

Prevents 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.

That is, the nohup command actually separates the child process from the session it is in, and note that the Nohup command does not automatically turn the 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: 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. And then log back in, you can also connect to the previous new session.
The use of screen is as follows.

# Create a new session$ screen$ node server.js then, press CTRL + A and CTRL + D to 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, then press CT RL + 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 return 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 will 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 is generally only used in development, its greatest strength 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
Nine, 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.

How to start the Linux daemon

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.