0

I cobbled together a simple C++ app that dumps HID keycodes from /dev/input/event[x] into a named pipe on Linux. It logs to the console fine but when I read the named pipe from my node.js app, it randomly misses data events.

Relevant C++ code:

int fd;
char * myfifo = "/tmp/testfifo";
mkfifo(myfifo, 0660);
fd = open(myfifo, O_WRONLY);

while (1){

    value = ev[0].value;

    if (value != ' ' && ev[1].value == 1 && ev[1].type == 1) {

        string s = to_string(ev[1].code);
        char const *sop = (s + "\n").c_str();

        cout << sop;
        write(fd, sop, sizeof(sop));
    }
}

Relevant node.js code:

var fifo = '/tmp/testfifo';    
var fd = fs.openSync(fifo, 'r+');

fs.createReadStream(null, {fd:fd}).on('data', function (d) {
    console.log(d);
});

I'm guessing my method for reading the named pipe is flawed since the C++ output looks good but I know almost nothing about C++ so am not sure if I'm flushing the pipe properly on the C++ side or there is some sort of read throttle I need to tweak on the node.js side. Any ideas?

mr.freeze
  • 13,731
  • 5
  • 36
  • 42

1 Answers1

1

A couple of errors:

  • Statement char const *sop = (s + "\n").c_str(); produces a dangling reference because the temporary string produced by (s + "\n") gets destroyed after the statement has been evaluated.
  • write(fd, sop, sizeof(sop)); writes sizeof(char const*) bytes, whereas it should write strlen(sop) bytes.

A fix:

std::string sop = s + "\n";
write(fd, sop.data(), sop.size());
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271