1

我正在为 Chrome 编写一个使用本机主机消息传递的扩展程序。目标是让 Chrome 在应用模式下运行时在操作系统默认浏览器中打开链接。Chrome 通过管道实现本机主机消息传递到本机应用程序的标准输入和标准输出。这一切都很好,我已经让扩展程序与本机应用程序对话。我遇到的问题是前 4 个字节的数据包含以下字符串的长度,出于我的目的,它始终包含空字符。下面显示了一个示例 strace。处理这个问题的最佳方法是什么?我想使用像 cin 或 getline 这样的东西,如果可能的话,它会停止程序直到收到输入。

Process 27964 attached
read(0, "~\0\0\0\"http://stackoverflow.com/qu"..., 4096) = 130 
read(0, 

这是当前的 C++ 代码。我尝试过使用 cin.get 和 fgets 的变体,但它们不会等待输入,并且 Chrome 在循环运行异常后会终止程序。

#include <string>
#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
    for(;;) {
        string message;
        cin >> message;
        if(!message.length()) break;
        string cmd(string("xdg-open ") + message);
        system(cmd.c_str());
    }
    return 0;
}
4

1 回答 1

1

据我了解here,长度应该是本机字节顺序,所以你的编译器使用相同的字节序用于相同的CPU架构:

每条消息都使用 JSON、UTF-8 编码进行序列化,并以原生字节顺序的 32 位消息长度开头。

这意味着您可以先阅读长度:

uint32_t len;  
while (cin.read(reinterpret_cast<char*>(&len), sizeof (len))) // process the messages
{ 
    // you know the number of bytes in the message: just read them  
    string msg (len, ' ');  // string filled with blanks 
    if (!cin.read(&msg[0], len) ) 
        /* process unexpected error of missing bytes */;
    else /* process the message normally */   
}
于 2015-10-31T13:43:31.903 回答