Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writeline to already running process

Tags:

c#

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 a process by its id. That worked fine Then I tried to send something to its stdin. That threw an InvalidOperationException. Note: the exception occured when I tried to get the StandardInput, not when I tried to us WriteLine.

I believe I know why I got the exception. The process was not started by my application, so I never had the chance to set RedirectStandardInput to true.

My goal is to be able to use this app to send text to a python interactive console(or another language). I still want to be able to enter text myself to the python prompt, but I also want to give my app control too.

How do I do this?

like image 503
phil Avatar asked Nov 01 '22 02:11

phil


1 Answers

Well, you hit the nail on the head. Unless you start the process yourself, you do not own the communication streams - and there isn't really a (reasonable) way around this.

If you run a console application by default, it runs in cmd - that's who owns the streams. If you want your application to "host" the process, you'll have to be the one who starts it. You'll just have to learn to call myHoster myApp instead of start myApp :)

You might also want to consider coding a PowerShell host. This would allow you to quite easily handle an interactive shell, though you'd have to learn to use PowerShell instead of CMD :) It's pretty easy to implement, PowerShell is really quite extensible.

like image 145
Luaan Avatar answered Nov 15 '22 05:11

Luaan