我正在使用 System.Diagnostics.Process.Start() 在 Linux 操作系统上远程启动命令。到目前为止,我已经能够启动简单的命令,然后读取输出。
例如我可以执行命令echo Hello World
并阅读Hello World
作为其输出。
这是简化的代码:
public void Execute(string file, string args) {
Process process = new Process {
StartInfo = {
FileName = file,
Arguments = args,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
}
};
process.Start();
}
为了更清楚,我使用上面的代码,如下所示:Execute("echo", "Hello World");
.
这是我的问题:只要我执行简单的命令,一切都会顺利进行,但我想使用管道和重定向来启动命令,以便对命令及其输出有更强的控制(不将输出本身处理为文本) )。
那么,是否有解决方法(或者可能是特定的库)来实现此结果?
为了在 Linux 中使用所有 shell 功能(包括管道、重定向等)执行命令,请使用以下代码:
public static Process ExecuteInBash(string command)
{
var process = new Process
{
StartInfo =
{
FileName = "bash",
ArgumentList = { "-c", "--", command },
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false
}
};
process.Start();
return process;
}
请注意,此方法是非阻塞的,它启动进程并且不等待它完成。为了阻止你必须调用process.WaitForExit()
方法。另外,最好检查一下退出代码 https://www.gnu.org/software/bash/manual/bash.html#Exit-Status查看命令是否成功或失败。例子:
var process = ExecuteInBash("echo Hello");
process.WaitForExit();
var standardOutput = process.StandardOutput.ReadToEnd();
var standardError = process.StandardError.ReadToEnd();
if (process.ExitCode == 0)
{
// Command succeeded.
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)