Writeline for an already running process

Here is my code:

static void Main(string[] args) { if(args.Length > 1) { int id; if(int.TryParse(args[0], out id)) { try { var p = Process.GetProcessById(id); p.StandardInput.WriteLine(args[1]); } catch (ArgumentException) { Console.WriteLine($"Couldn't find process with id {id}"); } } else { Console.WriteLine($"Couldn't find process with id {args[0]}"); } } } 

I got the process by its id. This worked fine. Then I tried to send something to its stdin. This threw an InvalidOperationException. Note. An exception occurred when I tried to get StandardInput, and not when I tried WriteLine to us.

I think I know why I got the exception. My process was not started, so I never had the opportunity to set RedirectStandardInput to true.

My goal is to use this application to send text to the python interactive console (or another language). I still want to be able to type the text myself into the python tooltip, but I also want to give my application control.

How to do it?

+5
source share
1 answer

Well, you hit a nail on the head. If you do not start the process yourself, you do not own communication flows - and in fact there is no (reasonable) way to get around this.

If you run the console application by default, it works in cmd - the one who owns the threads. If you want your application to accept the process, you must be the one who runs it. You just need to learn to call myHoster myApp instead of start myApp :)

You may also consider coding the PowerShell host. This will allow you to easily deal with the interactive shell, although you will have to learn to use PowerShell instead of CMD :) This is pretty easy to implement, PowerShell is really quite extensible.

+2
source

All Articles