tags:

views:

290

answers:

4

I have a Windows service(C#), that sprawns few child native processes (C++).

I'd like to gently kill those processes once in a while. (gently = let the procs to finalize its work before going down).

I tried to use the SetConsoleCtrlHandler() routine to register the child procs to console events and to call the CloseMainWindow() from the C# code to raise the "close console" events.

This didn't work for me. Mainly because the child processes are not console applications.

Does anyone knows what other methods can be used in order to fulfill this requirement?

A: 

C# has a native way to access the services running. You will need the "System.ServiceProcess" namespace, and the code should look kind of like this:

ServiceController[] services = ServiceController.GetServices(); 
for(int i = 0; i <  services.Length; i++)   
    {
       if (services[i].DisplayName == "COM+ System Application")  
            { 
               if (sc.Status == ServiceControllerStatus.Running) 
         { 
      sc.Stop(); 
         } 
     if (sc.Status == ServiceControllerStatus.Stopped) 
         { 
      sc.Start(); 
         } 
             } 
    } 
   }
Stephen Wrighton
My understanding is that the spawn children are not services on their own. Right?
Serge - appTranslator
@Serge - Actually it doesn't say. They are described as "processes" and describes trying to close them as if they were external console applications, so I made the assumption they were.
Stephen Wrighton
+4  A: 

Kernel event objects come to mind: your "manager" raises a named event. Your child processes should check the state of this event at least once in a while (or have a thread that continuously checks it).

Serge - appTranslator
+2  A: 

Post a message to the child processes. This can be a message of your own choosing, so you can pick up on the message in the child processes, and then do what needs to be done, see WM_USER.

Kris Kumler
This requires the children to have a message pump. Console apps typically don't have them. And since you have some issues getting to a/the terminal session from a service, I'd bet the children are console apps.
MSalters
A: 

Have a look at the technique of using QueueUserAPC and exceptions I described here. You might find it useful.

Roddy