【问题标题】:Cannot read STDOut from Process that is running in background无法从后台运行的进程中读取 STDOut
【发布时间】:2018-08-03 09:32:40
【问题描述】:

因此,在 Linux 下,我必须通过命令rfcomm connect hci0 xx:xx:xx:xx:xx:xx 连接到蓝牙设备,该命令会启动蓝牙连接,但必须保持运行才能保持连接。

我必须将所有内容都编写为 .NET Core 程序

运行命令几秒钟后输出以下行: Connected /dev/rfcomm0 to xx:xx:xx:xx:xx:xx on channel 1 Press CTRL-C for hangup

从那个输出我必须得到/dev/rfcomm0 部分,所以我可以用SerialPortReader 读取它,如果出现问题,比如,假设没有更多数据传入,我必须终止进程然后重新开始,直到我有一个良好的连接。

现在我的逻辑是这样的:

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;

我确实检查了输出是否没有重定向到像 STDErr 之类的东西,但是不,它是 100% 用 STDOut 编写的。

我已经尝试了一个逻辑,比如处理 StandardOutput 事件的 EventHandler,以及我异步读取它的逻辑,但都没有成功。所有人都有同样的问题,他们都阻塞了Read(); 函数。我的猜测是内部缓冲区可能没有正确刷新。

也许这里有人知道我的问题的答案。 P.S.:我知道我的代码不是最好的或最优化的,但它仍然应该可以工作,因为我已经在 Windows 下使用另一个阻塞命令尝试过它并且它有效。

提前感谢我得到的每一个帮助。

【问题讨论】:

    标签: c# linux process bluetooth .net-core


    【解决方案1】:

    我通过不直接运行命令解决了这个问题,因为这会引发缓冲区问题,所以我现在不运行命令rfcomm connect hci0 xx:xx:xx:xx:xx:xx,而是运行stdbuf -o0 rfcomm connect hci0 xx:xx:xx:xx:xx:xx,以避免出现缓冲问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 2014-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多