Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to start the Linux daemon

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces "how to start the Linux daemon" in detail, the content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to start the Linux daemon" can help you solve your doubts.

A "daemon" is a daemon that runs in the background all the time.

I. the origin of the problem

After the web app 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 the simplest node application, server.js, with only six lines.

Var http = require ('http'); http.createserver (function (req, res) {res.writehead (200,{' content-type': 'text/plain'}); res.end (' hello world');}) .subscription (5000)

You start it at the command line.

$node server.js

Everything seems to be fine, and everyone can happily access port 5000. However, once you exit the command line window, the application exits together and cannot be accessed.

How can it become the daemon of the system, become a service, and run there all the time?

II. Foreground tasks and background tasks

The script started above is called a foreground task (foreground job). It monopolizes the command line window and cannot execute other commands until it has finished running or manually aborted.

The first step in becoming a daemon is to change it to a "background job".

$node server.js &

As long as you add a symbol & to the end of the command, the started process becomes a "background task". If you want to change a running foreground task to a background task, press ctrl + z and then execute the bg command (let the most recently paused background task continue).

"background tasks" have two characteristics.

Inherits the standard output (stdout) and standard error (stderr) of the current session (conversation). As a result, all output from background tasks is still displayed synchronously on the command line.

The standard input (stdin) of the current session is no longer inherited. You can't enter instructions into this task. If it tries to read standard input, it pauses execution (halt).

As you can see, there is only one essential difference between "background task" and "foreground task": whether or not to inherit standard input. Therefore, while performing background tasks, the user can also enter other commands.

3. Sighup signal

When it becomes a "background task", does a process become a daemon? In other words, will the "background task" continue to be executed after the user quits session?

The linux system is designed in this way.

The user is ready to exit session

The system sends a sighup signal to the session

Session sends sighup signals to all child processes

After receiving the sighup signal, the child process automatically exits

The above process explains why the "foreground task" exits with the exit of session: because it receives a sighup signal.

So, will the "background task" also receive a 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 off by default (off). Therefore, when session exits, the sighup signal is not sent to the "background task". So, generally speaking, "background tasks" do not exit with session.

4. Disown command

It is not safe to start daemons through background tasks, because some systems may have huponexit parameters turned on (on).

A safer way is to use the disown command. It removes the specified task from the background tasks list (the result returned by the jobs command). Session will certainly not send a sighup signal to a "background task" as long as it is not on this list.

$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 will be no such process in the output.

The usage of disown is as follows.

# remove the most recent background task in progress $disown# remove all ongoing background tasks $disown-r # remove all background tasks $disown-a # do not remove background tasks, but let them not receive sighup signals $disown-h # according to jobid, remove the specified background task $disown% 2$ disown-h% 2

5. Standard iCompo

After using the disown command, there is one more problem. That is, after exiting the session, if the background process interacts with the standard iUnix o, it will still die.

Take the above script as an example, now add a line.

Var http = require ('http'); http.createserver (function (req, res) {console.log (' server starts...'); / / join this line res.writehead (200,{ 'content-type':' text/plain'}); res.end ('hello world');}) .subscription (5000)

Start the script above, and then execute the disown command.

$node server.js & $disown

Then, you exit session, access port 5000, you will find that the connection is not available.

This is because the standard iUnip o of "background tasks" inherited from the current session,disown command does not change this. Once the "background task" reads and writes the standard iUnip o, it will be found that it no longer exists, so an error will be reported to terminate execution.

To solve this problem, you need to redirect the standard iUnix o of "background tasks".

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

If the above is carried out in this way, there will basically be no problem.

VI. Nohup command

There is a more convenient command than disown, which is nohub.

$nohup node server.js &

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

Prevent sighup signals from being sent to this process.

Turn off standard input. The process can no longer receive any input, even if it is running in the foreground.

Redirect standard output and standard error to the file nohup.out.

That is, the nohup command actually separates the child process from the session in which it resides.

Note that the nohup command does not automatically turn the process into a "background task", so the & symbol must be added.

7. Screen command and tmux command

Another idea is to use terminal multiplexer (terminal multiplexer: managing multiple session on the same terminal), typically screen commands and tmux commands.

They can create another session in the current session. In this way, once the current session ends, it does not affect other session. Also, if you log in again later, you can also connect to the session you created earlier.

The usage of screen is as follows.

# create a new session$ screen$ node server.js

Then, press ctrl + an and ctrl + d to return to the original session and log out from there. The next time you log in, cut back.

$screen-r

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

$screen-s name# switches back to the specified session$ screen-r name$ screen-r pid_number# to list all session$ screen-ls

If you want to stop a session, switch back to it, and then press ctrl + c and ctrl + d.

Tmux is more and 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 way is to press ctrl + b and d, or you can go back to the original session.

# the next time you log in, the service session$ tmux attach is running at the backend.

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

# New session$ tmux new-s session_name# switches to the specified session$ tmux attach-t session_name# lists all session$ tmux list-sessions# exits the current session, returns the previous session$ tmux detach# to kill the specified session$ tmux kill-session-t session-name

VIII. Node tools

For node applications, without the above methods, there are some special tools for launching: forever,nodemon and pm2.

The simple function of forever is to ensure that the application will restart automatically when the process exits.

# start $forever server.js# as a foreground task start $forever start app.js# stop service process $forever stop id# restart service process $forever restart id# monitor changes in files in the current directory, restart $forever-w server.js#-m parameter specify maximum number of restarts $forever-m 5 server.js# list all processes $forever list

Nodemon is generally used only during development, and its greatest strength lies in the watch function, which automatically restarts the process as soon as the file changes.

# default to monitor changes in files in the current directory $nodemon server.js# monitors changes in specified files $nodemon-- watch app-- watch libs server.js

Pm2 is the most powerful, collecting logs and monitoring in real time in addition to restarting the process.

# start the application $pm2 start app.js# specify how many processes start at the same time (determined by the number of cpu cores), form a cluster $pm2 start app.js-I max# list all tasks $pm2 list# stop specified tasks $pm2 stop "restart specified tasks $pm2 restart" delete specified tasks $pm2 delete "save all current tasks" You can later restore $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 the web interface http://localhost:9615$ pm2 web

10. Systemd

In addition to specialized tools, the linux system has its own daemon management tool, systemd. It is a part of the operating system, directly interacts with the kernel, excellent performance, extremely powerful. We can give the program to systemd, let the system unified management, and become a real system service.

After reading this, the article "how to start the Linux daemon" has been introduced. If you want to master the knowledge of this article, you still need to practice and use it. If you want to know more about the article, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report