简体   繁体   English

生成进程时如何重定向标准输出

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

I've built a webservice for an internal server that I want to send a command to and have it launch a process. 我为内部服务器构建了一个Web服务,我想向该服务器发送命令并启动一个进程。 So I want to send a command to it like this: 所以我想像这样发送命令:

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

The endpoint would then do something like this: 然后,端点将执行以下操作:

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())
}

I want to be able to capture all the error messages and standard output generated by the executable. 我希望能够捕获可执行文件生成的所有错误消息和标准输出。 The executable could be anything like a console application or a powershell script. 可执行文件可以是控制台应用程序或Powershell脚本之类的东西。 What's the best approach for doing something like this? 做这样的事情的最佳方法是什么?

Use proc.StandardOutput.ReadToEnd() to read the redirected output stream to the end, and return that. 使用proc.StandardOutput.ReadToEnd()将重定向的输出流读取到末尾,并将其返回。

You may also want to set RedirectStandardError to True and do the same thing with proc.StandardError to get the error messages. 您可能还需要将RedirectStandardError设置为True,并使用proc.StandardError进行相同的操作以获取错误消息。 You can spawn a background thread to synchronously read standard error alongside the reading of standard output in the main thread. 您可以生成一个后台线程来同步读取标准错误,同时读取主线程中的标准输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 流程重定向标准输出详细程度问题 - Process redirect standard output verbosity issue 如何在C#、. net中仅异步重定向标准错误流而不是进程的标准输出流 - How to asynchronously redirect ONLY standard error stream and not standard output stream of a process in C#, .net 如何在Windows窗体应用程序中的c#中将标准输出重定向到psexec进程中的文件 - How to redirect standard output to a file from psexec process in c# within a Windows Forms Application 流程执行期间不会刷新重定向标准输出 - Redirect standard output isn't flushed during process execution C#:重定向已经运行的进程的标准输出 - C#: Redirect Standard Output of a Process that is Already Running 尝试重定向标准和/或错误时无输出。 我如何从中读取输出? - No output when trying to redirect standard and/or error. How can i read the output from this? 产生不同输出的控制台子进程 - spawning console sub process with different output 如何在后台启动进程并读取标准 output - How to start a process in the background and read standard output 如何获取父进程标准输出? - How to grab parent process standard output? 当UseShellExecute == false时,如何在C#进程上强制输出标准输出? - How do I force standard output on a C# Process when UseShellExecute == false?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM