C#双向IPC通过标准输入输出流实现

8

我该如何连接两个C#进程,使它们能够通过标准输入和标准输出进行通信?

就像这样:

进程A --> 标准输出A --> 标准输入B ---> 进程B

进程A <-- 标准输入A <-- 标准输出B <--- 进程B

1个回答

5
using System;
using System.Diagnostics;

class Program
{
  static void Main(string[] args)
  {
    string name;
    if (args.Length > 0 && args[0] == "slave")
    {
      name = "slave";
    }
    else
    {
      name = "master";
      var info = new ProcessStartInfo();
      info.FileName = "BidirConsole.exe";
      info.Arguments = "slave";
      info.RedirectStandardInput = true;
      info.RedirectStandardOutput = true;
      info.UseShellExecute = false;
      var other = Process.Start(info);
      Console.SetIn(other.StandardOutput);
      Console.SetOut(other.StandardInput);
    }
    Console.WriteLine(name + " started.");
    while (true)
    {
      var incoming = Console.ReadLine();
      var outgoing = name + " got : " + incoming;
      Console.WriteLine(outgoing);
      System.Threading.Thread.Sleep(100);
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接