Detailed explanation of the service process in Node


project in node deployment, often involves three parties: the local client, springboard and a server (cluster). After triggering gitlab hook script git, you need to perform the stepping stones in the appropriate ssh command shell file to start the node server, which requires the use of a commonly used commands setsid, such as ssh command is complete after the shell exits, node server is still running normally At this time node server process is one of the most typical daemon process (background service process).

Then, in the node project, how to create a daemon process? The simplest way, in fact, by way similar to the above described:

copy the code Code as follows:

require ( ‘ child_process’.) exec ( ‘setsid node app.js> / dev / null 2> & 1 &’);

this allows for daemon processes performed by way of the shell. But is not the focus of this article describes this “command-line” approach to achieve daemon process, but this article will describe in detail the principles to create daemon process, let me see below.


In the current business, the reason why you need to create daemon process is created in order to ensure interruption of the process parent process (ctrl + c) or parent process is finished after not affect the execution daemon process. Two implementations are described below, to achieve slightly different details on principle.

all discussed hereinbelow are carried out in the linux environment.

achieved a

In linux system, the parent process creates a child process, the parent process at this time if the exit, this time the child then becomes orphaned, its ppid to 1, that is a child process of init process. In node environment, if you do not do for the child processes stdioSome special handling parent processes do not really exit, but until the sub-process is completed, then exit. This happens because the Node creates a sub-process, which defaults to the child process to pass the output of the sub-process to the Stream of the child process (CHildProcess.stdout, ChildProcess.stderr), providing output sub-process messages in the parent process. Ability.

Therefore, resolving the STDIO to the child process to re-value:

  File: Parent.jslet CP = Require ('Child_Process '); const sp = cp.spawn (' Node ', [' ./ C.JS '], {stdio: [process.stdin, process.stdout, process.stderr]}); settimeout (() => { Console.log ('Parent Out')}, 5000); -------------- File: c.jssettimeout (() => {Console.log ('Children Exit');} , 10000)  
By setting the STDIO of the sub-process in the parent.js as the current terminal (actually inherits the STDIO of the parent process, the parent process is exited after 5s. At this point, the PPID of the sub-process becomes 1,10s after the sub-process exits.

The above implementation only satisfies the “parent process normal exit, sub-process into a daemon”, once the end of the “Ctrl + C” is the end-parent process, the child process will still exit, which is also achieved with the Node underlayer related. The default “Ctrl + C” triggers the SIGINT signal, the parent process is sent to the child process after accepting the signal, and if the child process exists, the function is executed, otherwise the Exit system adjustment sub-process exits. So if you want to get a child process is receiving SIGINT signals do not exit, only need to be processed:

File: c.jsprocess.on (‘sigint’, function () {Console.log ‘Child Sigint’);}; setTimeout (() => {console.log (‘child exit’);}, 10000)
 The above implementation can be satisfied We initially specified the goals: "The parent process exits or interrupts, the child process is still running."   
Implementation of the two

Node officially provides the relevant API for the creation of the Daemon process. If you don’t read the document, it is not easy to find this feature. There is a spawn function in the child_process module, and the shell command and its related options can be executed via SPAWN, while SpaWN provides some options for creating sub-process, where “Detached” option is closely related to our needs.

The Detached option allows Node nort-raising to create a Daemon process, setting up DATACHED, can create a new session and process group, the PID of the child process is the newly created process group, which starts with Setsid To the same role. The child process is already in two sessions and its parent process, so the exit and interrupt signals of the parent process will not pass to the child process, and the child process does not accept the interrupt signal of the parent process nature. When the parent process ends, the child process becomes a orphan process, which is received by the init process, and the PPID is set to 1.

FILE: Parent.jslet CP = Require (‘child_process “; const sp = cp.spawn (‘ Node ‘, [‘ ./ C.js ‘], {DETAChed: true, stdio: [process.stdin, process.stdout, process.stdout]}; sp.unref (); settimeout (() => {Console.log (‘Parent out’)}, 5000); ——————— File: c.jssettimeout (() => {Console.log (‘Children Exit’);}, 100000)

At this point, the C.js file does not set the sigint event listening function, and it will still run normally after the parent process is interrupted, which is because of the two session due to its and the parent process.

Set the sp.unref () function in the Parent.js file, the purpose is to “avoid the parent process waiting for the sub-process exit”. So why do you have mentioned? This is related to the Node’s event loop, allowing the parent’s event loop to exclude reference to the ChildProcess child process object, allowing the parent process to exit separately.

  Why can the two methods described above implement the daemon process? This has to return to the system level for analysis. There are several steps to create a daemon process in the Linux system:  
1. The parent process creates a sub-process, the parent process exits, let the child process be an orphan process, PPID = 1

2. Create a new session and process group through the setsid command or function to create a new session and process group

3. Set the current directory

4. Set file permissions, and Close the FD

of the FD

of the parent process inheritance, is the concept of multi-user multi-user in Linux multi-task. The process of different sessions cannot be communicated, so the parent child process is isolated. The execution of the setsid command allows the child to have a new feature:

The child process is out of the session control in the parent process, and the two independently does not affect the process group where the child is in the process group where the child is located

child process is out of date. The command line terminal, the terminal exits does not affect the sub-process

Review the method of one and method two, the discovery method is not true DAEMON process, just by listening-related interrupt signals Setting the NOP function (not performing the default interrupt behavior) guarantee the child process to continue to run; the method is the standard DEAMON process creation method, preferred!

The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Clouds.

© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment