Listen for terminal session "close" event
Asked Answered
G

1

6

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.

Gibbosity answered 16/11, 2016 at 4:3 Comment(0)
C
10

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);
  });
});
Cambyses answered 19/11, 2016 at 4:46 Comment(1)
This other question has the list of all the possible signals in a nice layout and explained: #4042701Gargle

© 2022 - 2024 — McMap. All rights reserved.