5

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

What I am afraid of, is if the user (in some cases, me) closes the terminal window without sending process A or B a SIGINT. What could then happen is that process B will still attempt to write to the terminal even though it's been closed by the user. Worse, the user could open a new terminal window and it might assume the same identity / file descriptor that the other terminal had and then subsequently get written to by process B.

Basically, I am looking for a way to "listen" for terminal session events like terminal sessions being closed.

Is it possible to listen for such events inside a Node.js process? Perhaps there is a corresponding handler similar to process.on('SIGINT')?

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

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

9

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);
  });
});
rishat
  • 8,206
  • 4
  • 44
  • 69
  • 1
    This other question has the list of all the possible signals in a nice layout and explained: https://stackoverflow.com/questions/4042201/how-does-sigint-relate-to-the-other-termination-signals-such-as-sigterm-sigquit#answer-29659703 – Alejandro Sanchez Jul 14 '21 at 15:57