簡體   English   中英

生成進程時如何重定向標准輸出

[英]How to redirect standard output when spawning a process

我為內部服務器構建了一個Web服務,我想向該服務器發送命令並啟動一個進程。 所以我想像這樣發送命令:

http://machine:999/execute?path=c:\scripts\dostuff.exe&args=-test

然后,端點將執行以下操作:

public ActionResult(string path, string args)
{

    var proc = new System.Diagnostics.Process();
    proc.StartInfo.FileName = path;
    proc.StartInfo.Arguments = args;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    proc.StartInfo.RedirectStandardOutput = true;

    //Hook into all standard output here

    //Block until process is returned - Async Controller action

    return Content(output.ToString())
}

我希望能夠捕獲可執行文件生成的所有錯誤消息和標准輸出。 可執行文件可以是控制台應用程序或Powershell腳本之類的東西。 做這樣的事情的最佳方法是什么?

使用proc.StandardOutput.ReadToEnd()將重定向的輸出流讀取到末尾,並將其返回。

您可能還需要將RedirectStandardError設置為True,並使用proc.StandardError進行相同的操作以獲取錯誤消息。 您可以生成一個后台線程來同步讀取標准錯誤,同時讀取主線程中的標准輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM