c# - 无法从后台运行的进程中读取 STDOut

标签 c# linux process bluetooth .net-core

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

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

运行命令几秒钟后输出以下行: 将/dev/rfcomm0 连接到 channel 1 上的 xx:xx:xx:xx:xx:xx 按 CTRL-C 挂断电话

从那个输出我必须得到 /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 下使用另一个阻塞命令尝试过它并且它有效。

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

最佳答案

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

关于c# - 无法从后台运行的进程中读取 STDOut,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51669573/

相关文章:

c# - 从 .exe 获取 FileDescription (ProgramName)

java - mysqldump 从 java 运行时返回代码 6,但相同的命令在命令行中运行良好

c# - 使用不同的命令多次使用 sql 命令

linux - 如何在 linux 上拦截 IP 数据包

r - Linux 上带有特殊字符 ($) 的密码(mount 语句)

Windows,多进程与多线程

c# - 如何在 Windows Phone 8.1 中使用 WCF 服务

c# - 在构造函数中使用 'this' 关键字

c# - 在 C# 中使用 graphics.drawimage 方法

json - 使用 JQ 或任何 Linux 工具删除或解析 JSON 文件中的数据