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 读取 字节 阻塞 通信 通过 服务器 C++ stdout 客户端      更新时间:2023-10-16

这是一个关于通过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.
  }
}