I am attempting bidirectional communication (IPC) between 2 C# Apps using only Standard Input streams. The parent app launches the child app with a Process, where RedirectStandardInput = true. So the parent process is able to send commands to the child process using childProc.StandardInput.WriteLine(). I am capturing these messages asynchronously using BeginRead() and EndRead() of the stream acquired with Console.OpenStandardInput(). Parent to child communication is working great. I am able to send and receive messages asynchronously.
But when the child attempts to write to the parent, using the same code, .NET throws this error:
StandardInput has not been redirected.
So, in simple terms, how does a .NET app redirect its own standard input stream? I will then redirect the standard input stream of my parent process, so the child can send messages to it.
My parent process is a WinForms C# App built with .NET 4.0 x86.
Edit: Here is the code of the IPC Server
internal class IPCServer {
private Stream cmdStream;
private byte[] cmdBuffer = new byte[4096];
public IPCServer() {
cmdStream = Console.OpenStandardInput(4096);
GetNextCmd();
}
private void GetNextCmd() {
// wait for next
cmdStream.BeginRead(cmdBuffer, 0, cmdBuffer.Length, CmdRecived, null);
}
private void CmdRecived(IAsyncResult ar) {
// input read asynchronously completed
int bytesRead = 0;
try {
bytesRead = cmdStream.EndRead(ar);
} catch (Exception) { }
if (bytesRead > 0) {
// accept cmd
.........
// wait for next
GetNextCmd();
}
}
}
And here is the code of the IPC Client
internal class IPCClient {
private Process appProc;
public IPCClient(Process appProcess) {
if (!appProcess.StartInfo.RedirectStandardInput) {
//MessageBox.Show("IPCClient : StandardInput for process '" + appProcess.ProcessName + "' has not been 'redirected'!");
return;
}
appProc = appProcess;
}
public void SendCmd(string cmd) {
if (appProc != null) {
appProc.StandardInput.WriteLine(cmd);
}
}
}
In the parent process:
// open child app
ProcessStartInfo info = new ProcessStartInfo(childProcPath, args);
info.WorkingDirectory = childProcDir;
info.LoadUserProfile = true;
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardOutput = true;
info.RedirectStandardInput = true;
childProc = Process.Start(info);
// connect to app for IPC
Client = new IPCClient();
Client.Init(childProc);
// recieve cmds from app
Server = new IPCServer();
Server.OnCmdRecieved = GotCmd;
Server.Init();
In the child process:
ownerProcess = ....
Server = new IPCServer();
Server.OnCmdRecieved = GotCmd;
Server.Init();
Client = new IPCClient();
Client.Init(ownerProcess);