2015-10-31 39 views
1

我正在爲使用本地主機消息傳遞的Chrome編寫擴展。目標是讓Chrome在應用程序模式下運行時在OS默認瀏覽器中打開鏈接。 Chrome通過管道將本地主機消息傳遞到本地應用程序的標準輸入和標準輸出。這一切都很好,我有擴展與本地應用程序交談。我遇到的問題是數據的前4個字節包含以下字符串的長度,這對我而言總是包含空字符。下面顯示了一個strace示例。處理這個問題的最佳方法是什麼?我想使用類似cin或getline的東西,這會阻止程序,直到收到輸入爲止。處理C++中stdin中的空字符

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; 
} 
+1

請張貼一些代碼。 –

回答

1

據我瞭解here,長度應在本地字節順序,讓你的編譯器使用了相同的CPU架構相同的字節順序:

each message is serialized using JSON, UTF-8 encoded and is preceded with 32-bit message length in native byte order.

這意味着,你可以閱讀第一長度:

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 */ 
} 
+0

編譯器不喜歡那樣。 '錯誤:沒有匹配函數調用'std :: basic_istream :: read(uint32_t *,long unsigned int)'' '注意:沒有已知的轉換參數1從'uint32_t * {aka unsigned int *}' to'std :: basic_istream :: char_type * {aka char *}'' –

+0

@ spike.barnett對不起:需要強制轉換以符合read()的expectatinos。我編輯過。 – Christophe

+0

這樣做,謝謝一堆。另外,我甚至不知道reinterpret_cast存在。我必須詳細閱讀。 –