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?

3
  • Check the value of fd in C++ code. Commented Sep 25, 2017 at 16:52
  • Value looks good. I think it's definitely on the node.js side because when I use spawn to tail the same pipe it works great. Very interesting. Commented Sep 26, 2017 at 0:08
  • This javascript works for me, even with simpler fs.createReadStream('/tmp/testfifo').on(...). Commented Sep 26, 2017 at 17:24

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the reply. Unfortunately that change didn't have any effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.