【问题标题】:Exception when reading output of process读取进程输出时出现异常
【发布时间】:2018-10-29 22:49:12
【问题描述】:

我的问题如下:

我在 Visual Studio 中使用 C++/CLI 创建了一个 UI。 现在我有一个按钮事件,它创建了一个运行带有参数的 C++ 控制台应用程序的进程。

这很好用,控制台应用程序使用参数执行,没有错误,并且我还看到了带有正确输出的控制台窗口。

但我仍然遇到异常:

StandardOut 尚未重定向或进程尚未开始。

我认为这与 Streamreader 和一些 DataReceivedEvents 有关,但我不知道。

这是我的代码:

try {

        String^ parameters = tbLoadXML->Text + " " + tbNumberAnts->Text + " " + tbIteration->Text + " " + tbReduction->Text + " " + tbPheromoneDeposit->Text + " " + tbPheromoneReduction->Text + " " + tbAlpha->Text + " " + tbBeta->Text + " " + reduce.ToString() + " " + algorithm.ToString() + " " + probabilityalgorithm.ToString() + " " + numbercities.ToString();

        Process^ process = gcnew Process();
        process->StartInfo->UseShellExecute = false;
        process->StartInfo->CreateNoWindow = true;      
        process->StartInfo->RedirectStandardOutput = true;
        process->Start("TSPACO.exe", parameters);

        StreamReader^ reader = process->StandardOutput;
        String^ output = reader->ReadToEnd();       

        textBox1->Text += output;

        process->WaitForExit();
        process->Close();
    }
    catch (Exception^ ex) {
        MessageBox::Show(ex->Message);
    }   

我也尝试了一个while循环:

while (!process->StandardOutput->EndOfStream)
{
            textBox1->Text += process->StandardOutput->ReadLine();
}

但没有什么真正有效 - 我不知道为什么。

【问题讨论】:

  • 你不检查进程是否已经真正启动。相对文件路径通常是有问题的。尝试将进程的绝对路径作为Process::Start() 方法的第一个参数传递。

标签: c++ command-line process c++-cli clr


【解决方案1】:

所以我想出了一个解决我的问题的方法——我不知道为什么会这样,但我认为诀窍是创建一个具有所有需要的属性的 ProcessStartInfo-Object,然后只使用 Process::Start without 的默认方法任何参数:

    ProcessStartInfo^ startInfo = gcnew ProcessStartInfo();
    startInfo->FileName = "TSPACO.exe";
    startInfo->Arguments = parameters;
    startInfo->UseShellExecute = false;
    startInfo->CreateNoWindow = true;
    startInfo->RedirectStandardOutput = true;

    Process^ process = gcnew Process();
    process->StartInfo = startInfo;
    process->Start();

    StreamReader^ reader = process->StandardOutput;
    String^ output = reader->ReadToEnd();

    textBox1->Text += output;

    process->WaitForExit();
    process->Close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 2016-08-24
    • 2012-04-02
    • 2020-12-12
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多