Listen to the close session of the terminal session

In the terminal, I start the background process A, which, in turn, starts the process B. Process B writes to the terminal (process A passed B the correct TTY file descriptor).

I am afraid if the user (in some cases, I) closes the terminal window without sending process A or B a SIGINT. Then it may happen that process B still tries to write to the terminal, even if it was closed by the user. Worse, the user can open a new terminal window, and he can accept the same identifier / file as another terminal, and then is recorded in process B.

Basically, I'm looking for a way to โ€œlistenโ€ for terminal session events, such as closing terminal sessions.

Is it possible to listen for such events inside the Node.js process? Perhaps there is an appropriate handler like process.on('SIGINT') ?

I assumed that the SIGTERM event was an event to listen to, but now, after experimenting with the code, don't think that it is.

+5
source share
1 answer

You should look for SIGHUP (see also all possible signals ):

 var http = require('http'); var fs = require('fs'); var server = http.createServer(function (req, res) { setTimeout(function () { //simulate a long request res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }, 4000); }).listen(9090, function (err) { console.log('listening http://localhost:9090/'); console.log('pid is ' + process.pid); }); process.on('SIGHUP', function () { fs.writeFileSync(`${process.env.PWD}/sighup.txt`, `It happened at ${new Date().toJSON()}`); server.close(function () { process.exit(0); }); }); 
+6
source

Source: https://habr.com/ru/post/1259799/


All Articles