Meh*_*dar 1 c++ bash ipc unix-socket node.js
我正在尝试在 Linux 中使用命名管道在 NodeJS 和 C 程序之间进行通信。我的服务器程序是用 NodeJS 编写的:
'use strict';
const net = require('net');
const pipename = '/tmp/pipe1';
const fs = require('fs');
let server = net.createServer(function(socket){
console.log('A new connection');
socket.on('data',function(data){
console.log(data.toString());
});
socket.on('end',function(){
console.log('Closed connection');
});
});
server.on('error',console.log);
fs.unlink(pipename,function(){
server.listen(pipename);
})
//Test unix-socket server:
setInterval(function(){
var stream = net.connect(pipename);
stream.on('error',console.log);
stream.write('hello');
stream.end();
},2000);
Run Code Online (Sandbox Code Playgroud)
但是,当我想在 NodeJS 服务器已经启动后打开 C 内部的管道时,我收到错误:
const char* pipename = "/tmp/pipe1";
int hPipe = open(pipename, O_WRONLY); //Error: No such device or address
Run Code Online (Sandbox Code Playgroud)
当我尝试去做时echo 'Hello World!' > /tmp/pipe1,我就成功了bash: /tmp/pipe1: No such device or address。但ls -l /tmp产量:
srwxr-xr-x 1 root root 0 Sep 16 03:20 pipe1
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
这/tmp/pipe1不是管道文件。这是一个套接字文件。这就是领先的s意思srwxr-xr-x。
和Bash的重定向一样,>不支持socket文件。您需要使用套接字 API 来打开文件。
使用strace (例如strace bash -c 'echo > /tmp/sockfile')我们可以看到:
...
openat(AT_FDCWD, "/tmp/sockfile", ...) = -1 ENXIO (No such device or address)
...
Run Code Online (Sandbox Code Playgroud)
所以错误代码是ENXIO,对应的错误信息是No such device or address。Bash 只是调用标准 C API(如strerror)来打印错误。
客户端示例代码:
...
openat(AT_FDCWD, "/tmp/sockfile", ...) = -1 ENXIO (No such device or address)
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
773 次 |
| 最近记录: |