I cannot get my nodejs application to quit using process.exit()
from within a signal handler. This is because I have a pending read operation on a Linux input event node (/dev/input/mouse1
). I have spent several hours researching, but all I could find was this SO question. I tried using an fs.ReadStream like it is used there and call its destroy
method, but it also did not work. Even by reading the nodejs source code I couldn't come up with an idea. Then there is this issue on github, which is somehow related.
So far, I came up with some hacks to work around this problem, but nothing clean:
- Use something stronger than
process.exit
, maybeprocess.abort
- Spawn a child process (
childProcess.fork
) toread
which I can terminate from the parent process. But this will create a new nodejs instance with ~10mb memory usage. - Write a program in a language (C++) where I have better control over what's going on (using threads etc.) and call this from javascript. Although I would prefer staying in js-land.
- Or maybe someone knows a tool which can help me achieve my goals in a different way? (See background information below). Maybe I don't have to use
/dev/input/
Basically, I need a way to cancel pending read
operations, either directly or indirectly (e.g. by clearing them from the active_handles
list).
Thanks in advance for your answers!
Example
In the code example below, I can press ctrl+c, but nodejs will only exit after I move my mouse:
'use strict'
const fs = require('fs');
const buf = new Buffer(24);
const mouse = fs.openSync('/dev/input/mouse1', 'r');
const onRead = (err, bytesRead, buffer) => {
console.log('read');
if (!err) {
process.nextTick(fs.read, mouse, buf, 0, buf.length, null, onRead);
}
};
fs.read(mouse, buf, 0, buf.length, null, onRead);
process.on('SIGINT', () => {
fs.closeSync(mouse);
process.exit();
});
Background information
I am working on a small project based on a raspberry pi running a nodejs script. I want the program to respond both to user input via a usb mouse's scroll wheel as well as a GPIO-attached button. Therefore, I make use of the onoff library for the GPIO stuff. The onoff
docs suggest to install a custom SIGINT handler to free resources before the program exits, so that's where this desire comes from. For handling the scroll wheel data without a window system or even a terminal, I eventually want to get this library to work, but now I have encountered the above problem.