因此,在 Linux 下,我必須通過命令連接到藍牙設備,該命令rfcomm connect hci0 xx:xx:xx:xx:xx:xx啟動藍牙連接,但必須保持運行才能保持連接。我必須將所有內(nèi)容都編寫為 .NET Core 程序幾秒鐘后運行該命令會輸出以下幾行: Connected /dev/rfcomm0 to xx:xx:xx:xx:xx:xx on channel 1Press CTRL-C for hangup從那個輸出我必須得到/dev/rfcomm0零件,所以我可以用 讀取它SerialPortReader,如果出現(xiàn)問題,比如,假設沒有更多數(shù)據(jù)傳入,我必須終止進程并重新開始,直到我有一個好的聯(lián)系?,F(xiàn)在我的邏輯是這樣的:while(!Terminate){ string port = Connect(); ReadData(port); BTProcess.Kill();}不要理會這個ReadData(port);功能,因為我的程序從來沒有接近過這個功能。本Connect()看起來是這樣的:while (!Connected){ Console.WriteLine("Configuring Process"); BTProcess = new Process(); BTProcess.StartInfo.FileName = "rfcomm"; BTProcess.StartInfo.Arguments = "connect hci0 xx:xx:xx:xx:xx:xx" BTProcess.StartInfo.RedirectStandardOutput = true; BTProcess.StartInfo.UseShellExecute = false; Console.WriteLine("Starting Process"); BTProcess.Start(); StreamReader reader = _BTProcess.StandardOutput; bool done = false; Console.WriteLine("Reading STDOUT now."); while (!done) // EDIT: If I do the while with !reader.EndOfStream then it won't even enter into the loop { Console.Write("-"); int c = reader.Read(); // Program stops in this line if(c != -1) { port += (char)c; } Console.Write(c); if (c == 0) { port = ""; done = true; _BTProcess.Kill(); } if (/* String Contains Logic blabla */) { port = /* The /dev/rfcomm0 stuff */ Connected = true; done = true; } } reader.Close();}return port;我已經(jīng)檢查過輸出是否沒有重定向到像 STDErr 之類的東西,但不,它是 100% 用 STDOut 編寫的。我已經(jīng)嘗試過類似處理標準輸出事件的 EventHandler 的邏輯,以及我異步讀取它的邏輯,但都沒有成功。所有人都有同樣的問題,他們都阻塞在Read();函數(shù)上。我的猜測是內(nèi)部緩沖區(qū)可能沒有正確刷新。也許這里有人知道我的問題的答案。PS:我知道我的代碼不是最好的或最優(yōu)化的,但它應該可以工作,因為我已經(jīng)在 Windows 下使用另一個阻塞命令嘗試過它并且它工作正常。預先感謝我得到的每一個幫助。
無法從后臺運行的進程中讀取 STDOut
慕田峪9158850
2021-11-14 14:39:32