以下是我從你的問題的理解:
a.exe
開始b.exe
a.exe
使用任何命令行參數或標準輸入的命令/請求傳遞到b.exe
b.exe
收到命令/請求並通過StandardOutput傳遞信息
使用命令行參數更簡單一點,除非您需要爲每個請求/命令多次運行b.exe
。
// b.exe
static void Main(string[] args)
{
// using command line arguments
foreach (var arg in args)
ProcessArg(arg);
// if using input, then use something like if processing line by line
// string line = Console.ReadLine();
// while (line != "exit" || !string.IsNullOrEmpty(line))
// ProcessArg(line);
// or you can read the input stream
var reader = new StreamReader(Console.OpenStandardInput());
var text = reader.ReadToEnd();
// TODO: parse the text and find the commands
}
static void ProcessArg(string arg)
{
if (arg == "help") Console.WriteLine("b.exe help output");
if (arg == "call") Console.WriteLine("b.exe call output");
if (arg == "command") Console.WriteLine("b.exe command output");
}
// a.exe
static void Main(string[] args)
{
// Testing -- Send help, call, command --> to b.exe
var psi = new ProcessStartInfo("b.exe", "help call command")
{
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
};
var p = new Process() { StartInfo = psi };
p.ErrorDataReceived += p_ErrorDataReceived;
p.OutputDataReceived += p_OutputDataReceived;
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
// if sending data through standard input (May need to use Write instead
// of WriteLine. May also need to send end of stream (0x04 or ^D/Ctrl-D)
StreamWriter writer = p.StandardInput;
writer.WriteLine("help");
writer.WriteLine("call");
writer.WriteLine("exit");
writer.Close();
p.WaitForExit();
}
static void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.Error.WriteLine("a.exe error: " + e.Data ?? "(null)");
}
static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("a.exe received: " + e.Data ?? "(null)");
}
看那OutputDataReceived和ErrorDataReceived事件以及這些方法的MSDN樣本。
其中一個考慮因素是您無法通過管理權限管理運行程序的輸出。您需要保存輸出,然後將輸出傳遞給其他程序。
我發現了一個有幫助的CSharpTest庫,其中有一個ProcessRunner類。例如,瀏覽ProcessRunner的「InternalStart」方法。
你需要應用程序或基本shell重定向嗎?即'a.exe | b.exe'? – 2014-11-04 16:39:29
我想實現一個應用程序可以調用b.exe的命令 – david 2014-11-04 16:43:31
b:請致電 b:help b:com1 – david 2014-11-04 16:43:59