简体   繁体   English

如何使用Process.Start启动管道并重定向命令?

[英]How can I launch pipes and redirects commands with Process.Start?

I'm using System.Diagnostics.Process.Start() to remotely launch commands on a Linux os. 我正在使用System.Diagnostics.Process.Start()在Linux操作系统上远程启动命令。 Until now I have been able to launch simple commands and then read the output. 到目前为止,我已经能够启动简单的命令,然后读取输出。
For example I can execute the command echo Hello World and read Hello World as its output. 例如,我可以执行命令echo Hello World并读取Hello World作为其输出。

Here's the simplified code: 这是简化的代码:

public void Execute(string file, string args) {
    Process process = new Process {
        StartInfo = {
            FileName = file,
            Arguments = args,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false
        }
    };
    process.Start();
}

To be clearer, I use the code above like this: Execute("echo", "Hello World"); 为了更清楚,我使用上面的代码: Execute("echo", "Hello World"); .

Here's my problem: as long as I execute simple commands everything works smooth, but I'd like to launch commands with pipes and redirects, in order to have a stronger control on the command and on its output (without handle the output itself as text). 这是我的问题:只要我执行简单的命令一切顺利,但我想用管道和重定向启动命令,以便对命令及其输出有更强的控制(无需将输出本身作为文本处理)。
So, is there a workaround (or maybe a specific library) to achieve this result? 那么,是否有解决方法(或者可能是特定的库)来实现这一结果?

In order to execute commands in Linux with all the shell features (including pipelines, redirections etc.) use the following code: 为了在Linux中执行具有所有shell功能(包括管道,重定向等)的命令,请使用以下代码:

public static void ExecuteInBash(string command)
{
    var process = new Process
    {
        StartInfo = 
        {
            FileName = "bash",
            Arguments = "-c \"" + command + "\"",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false
        }
    };
    process.Start();
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM