如何配置命令行启动的程序,允许其他程序向其输入数据?
问题
我有两个程序:ProgramA从控制台接收任意输入并直接输出;ProgramB为C#编写,需向ProgramA发送输入。ProgramA通过批处理文件以类似start ProgramA.exe的命令启动。在ProgramB中尝试访问ProgramA的StandardInput时,触发错误:System.InvalidOperationException: StandardIn has not been redirected。若通过ProgramB启动ProgramA,通常可设置process.StartInfo.RedirectStandardInput = true,但该操作对外部已启动的进程无效。请问需在启动ProgramA的命令中添加什么配置,才能让ProgramB访问其输入?
ProgramA 代码
internal class Program { static void Main(string[] args) { while (true) { Console.WriteLine("Input: "); string input = Console.ReadLine(); if (input.ToLower() == "q") break; else Console.WriteLine(input); } } }
ProgramB 代码
internal class Program { static void Main(string[] args) { Process programA = Process.GetProcessesByName("ProgramA")[0]; while (true) { Console.WriteLine("Input: "); string input = Console.ReadLine(); if (input.ToLower() == "q") break; else { if (programA == null) return; Console.WriteLine(programA.ProcessName + " : " + programA.ToString()); StreamWriter inputWriter = programA.StandardInput; inputWriter.WriteLine("input"); } } } }
解决方案
明确一点:无法通过修改启动ProgramA的命令行参数,让外部已启动的ProgramA允许其他进程访问其StandardInput。进程的标准输入重定向是启动时就确定的核心属性,一旦进程启动,无法再修改这个状态。
你需要换思路实现跨进程输入:
- 方案1:调整启动逻辑,让ProgramB负责启动ProgramA,启动时设置
RedirectStandardInput = true,这样就能直接通过StandardInput写入内容。 - 方案2:用进程间通信(IPC)机制替代标准输入,比如命名管道、共享内存或TCP套接字。例如让ProgramA监听命名管道,ProgramB通过管道发送数据,ProgramA接收后模拟原有输入处理逻辑。
以下是命名管道实现的简单示例:
修改后的ProgramA
using System.IO.Pipes; internal class Program { static void Main(string[] args) { using (var pipeServer = new NamedPipeServerStream("ProgramAPipe", PipeDirection.InOut)) { Console.WriteLine("等待连接..."); pipeServer.WaitForConnection(); using (var reader = new StreamReader(pipeServer)) using (var writer = new StreamWriter(pipeServer)) { writer.AutoFlush = true; while (true) { string input = reader.ReadLine(); if (input?.ToLower() == "q") break; Console.WriteLine($"收到输入: {input}"); writer.WriteLine($"已处理: {input}"); } } } } }
修改后的ProgramB
using System.IO.Pipes; internal class Program { static void Main(string[] args) { using (var pipeClient = new NamedPipeClientStream(".", "ProgramAPipe", PipeDirection.InOut)) { pipeClient.Connect(); using (var reader = new StreamReader(pipeClient)) using (var writer = new StreamWriter(pipeClient)) { writer.AutoFlush = true; while (true) { Console.WriteLine("请输入要发送的内容(输入q退出):"); string input = Console.ReadLine(); if (input.ToLower() == "q") break; writer.WriteLine(input); string response = reader.ReadLine(); Console.WriteLine($"ProgramA 返回: {response}"); } } } } }
内容的提问来源于stack exchange,提问作者this_is_a_display_name
相关产品推荐
相关产品推荐

