C#/ Mono - 从控制台应用程序读取输出

问题描述 投票:0回答:1

我目前正在编写一个程序,用作第二个控制台程序的接口,因此它应该读取该程序的输出,处理它并根据需要发回命令。

当我在Windows机器上的Visual Studio中测试我的代码时,一切正常。但是当我在我的Ubuntu机器上用Mono(xbuild)编译它时,我的程序无法读取控制台程序的输出(我没有得到任何例外或任何东西)

我的相关代码如下。我也尝试使用/bin/bash -c '/path/to/console_program'参数运行控制台程序作为ProcessStartInfo,看看其他人是怎么做的,但它给了我相同的静音结果。

    private static ProcessStartInfo startInfo;
    private static Process process;

    private static Thread listenThread;
    private delegate void Receive(string message);
    private static event Receive OnReceive;

    private static StreamWriter writer;
    private static StreamReader reader;
    private static StreamReader errorReader;

    public static void Start(bool isWindows)
    {
        if(isWindows)
            startInfo = new ProcessStartInfo("console_program.exe", "");
        else
            startInfo = new ProcessStartInfo("/path/to/console_program", "");

        startInfo.UseShellExecute = false;
        startInfo.CreateNoWindow = true;
        startInfo.ErrorDialog = false;

        startInfo.RedirectStandardError = true;
        startInfo.RedirectStandardInput = true;
        startInfo.RedirectStandardOutput = true;

        process = new Process();
        process.StartInfo = startInfo;
        bool processStarted = process.Start();

        Console.WriteLine("[LOG] Engine started: " + processStarted.ToString());

        writer = process.StandardInput;
        reader = process.StandardOutput;
        errorReader = process.StandardError;

        OnReceive += new Receive(Engine_OnReceive);

        listenThread = new Thread(new ThreadStart(Listen));
        listenThread.Start();
    }

    private static void Engine_OnReceive(string message)
    {
        Console.WriteLine(message);
    }

    private static void Listen()
    {
        while (process.Responding)
        {
            string message = reader.ReadLine();
            if (message != null)
            {
                OnReceive(message);
            }
        }
    }

在那里看到任何明显的错误,我应该修复它以使其在Linux方面工作?

c# linux mono console
1个回答
1
投票

你不应该使用process.Responding。相反,使用null检查来检测流的结束。即使不知道mono总是为false属性返回Responding(参见mono source code),这对我来说也是有意义的,因为终止(没有响应)进程的输出仍然可以被缓冲。

© www.soinside.com 2019 - 2024. All rights reserved.