C/C++服务器,通过stdin/stdout与客户端通信(阻塞stdin,直到读取了大量字节)
C/C++ server, communicating by stdin/stdout with clients (blocking on stdin until a number of bytes has been read)
这是一个关于通过stdin/stdout进行进程间通信的问题。
问题是我有一个COM库,我无法与任何Java COM桥一起使用(一个特定的函数总是会导致核心转储(。但我可以从C++程序中使用它。
因此,我决定用C++制作一个包装服务器程序来为我进行这些调用,并通过stdin/stdout从Java与它进行通信,但我在这里遇到了一个问题。我决定使用protobufs来通信消息,主要问题是读取C++端的输入我需要一个方法,该方法将阻塞,直到将一定数量的字节写入stdin以供读取
这个想法是使用谷歌的protobufs,并建立这样的通信:
- C程序启动一个无限循环,阻塞STDIN输入,等待获得4个字节,这将是传入消息的长度
- 然后它阻塞以获得整个消息(原始字节计数是已知的(
- 使用protobuf分析消息
- 做工作
- 将输出写入stdout(可能采用相同的方式,在消息前加上传入的字节数(
- Java clinet使用DataStream或类似的东西读取它,并使用protobufs进行解密
由于我对C++和Windows编程缺乏了解,建立这种双向通信比我想象的要困难得多(我使用MSVS2013社区编译它,所有这些COM代码中有很多特定于Windows的marcos/typedef(。
有没有第三方lib,可以让创建这样一个简单的服务器变得简单?
PS:可以是C,可以是C++,我只需要它在Windows上运行。
一个相对简单的消息处理循环可能是这样的。但是,您应该真正检查两次读取的返回值,并在那里处理错误。
void read_and_process_message(void) {
while(true) {
long nMessageBytes;
read(stdin, &nMessageBytes, sizeof(long));
//Convert from network byte-order to local byte order
nMessageBytes = ntohl(nMessageBytes);
char * buffer = malloc(nMessageBytes);
read(stdin, buffer, nMessageBytes);
// Do something with your buffer and write to stdout.
}
}
相关文章:
- 从stdin读取时子进程挂起(fork/dup2竞争条件)
- 异步提升从stdin读取的asio
- 使用管道从 STDIN 读取分叉进程时出现问题
- 使用 stdin 读取文本文件,然后遍历多个数组
- 如何在使用 gdb 调试期间从 stdin 读取
- C++:在数据写入管道时从 stdin 读取
- C++以缓冲速率从STDIN读取输入
- 使用重定向的stdin C++读取文件
- 从 Python 子进程中的 stdin 读取挂起在 C++/Python IPC 中
- Python等效于从stdin读取的C++代码
- 从 C++ 中的 STDIN 读取
- 从STDIN读取int时的奇怪行为
- QTextStream stdin读取行未暂停输入
- 如何从stdin读取字符串,直到遇到空行
- 为Windows编写一个非阻塞stdin读取函数
- 有没有办法只从C++中的stdin读取满足某些条件的字符
- 从Stdin读取文本文件
- 从stdin读取并将值存储到数组C++中
- 使用 select() 从 stdin 读取 - 以非阻塞方式
- 在C++中从 stdin 读取长度大于 4096 字节的字符串