【问题标题】:C#/Mono - Reading output from a console appC#/Mono - 从控制台应用程序读取输出
【发布时间】:2014-02-23 18:17:08
【问题描述】:

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

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

我的相关代码如下。在查看其他人的操作方式后,我还尝试使用ProcessStartInfo 参数以/bin/bash -c '/path/to/console_program' 运行控制台程序,但它给了我同样的静默结果。

    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】:

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

    【讨论】:

    • 如果你使用 mono 在 linux 上运行 winforms 应用程序呢?
    猜你喜欢
    • 2023-04-03
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多