tags:

views:

93

answers:

2

I'm trying to start a C# program running, and then give it command from the cmd.exe after it's started running. For instance, suppose I started my .exe from the command line (C://FILEPATH/my_program.exe). I'd then like to have that program continue running, and then have me be able to pass commands to it that it is capable of handling. In my ideal world this would be something like "C://FILEPATH/my_program.exe run_my_command()" which would execute the run_my_command function, or "C://FILEPATH/my_program.exe k", which would do something in response to the char k that I'd pre-programmed in. I know that, as I've typed, would start a new copy of my_program.exe. I'd only like to have one running while I pass something like that in.

Does anyone know how to do this? Sample code would be wonderfully appreciated. Thanks!!

+3  A: 

The simplest solution would be for your second instance of "my_program.exe" to look for an existing instance that's already running, "pass" the message over to it and then exit immediately.

The usual way this is implemented is via named pipes (System.IO.Pipes in .NET 3.5+). When your program starts up, listen on a named pipe with a given name. If there's something else already listening on that pipe, send the message to it and exit.

Dean Harding
+1, except I would recommend either remoting or WCF instead of named pipes as an inter-process communication method.
Kragen
@Kragen: What for? Overpower imo
abatishchev
@abatishchev - Named pipes are a low level mechanism - the responsibility is on you to define the protocol, handle errors as well as address any security concerns. .Net remoting / WCF are wrappers around named pipes (and other transport mechanisms) that provide all of the above and more - why go to the effort to write your own IPC mechanism based on named pipes, when one already exists?
Kragen
WCF can ease the handling of named pipes through the NetNamedPipesBinding, so I would recommend using it.
Johann Blais
+1  A: 

You are describing a typical service and command tool. The service (demon) runs in the background and executes commands. The command tool takes user commands and passes them to the service. See Windows Service Applications. Having a service instead of starting several processes takes care of some issues your approach has, like security isolation between the processes (eg. one user starts the a command, another user starts another command and gets executed in the context of the first user) and process lifetime issues (user launches a command and then closes his session).

The command tool would communicate with the process via classic IPC (local RPC, pipes, shared memory, etc).

Remus Rusanu