tags:

views:

65

answers:

3

I want to kill a process running on the machine using taskkill if they're still running after X seconds (a windows service was stopped but it takes time for processes to dissapear) What's the most correct way to accomplish the above in C# (.net 2.0 or possibly 3.0)?

I've utility method for verifying whether a process is still running, given the process name (using Process.GetProcesses()). (As the process is not spawned by my code, I can't use WaitTillExit to know when it's no longer running)

PS: the process runs on a remote machine

+5  A: 

You could call Process.WaitForExit, passing the appropriate timeout. This way you won't need to use your own check to see whether the process is still running.

Tim Robinson
I'm not sure how this achieves "killing" the process if it's till running after timeout has passed, though...
akapulko2020
I thought you were going to use taskkill?
Tim Robinson
`WaitForExit` returns `false` if the process is still running after the timeout; use this to determine whether to kill it
Tim Robinson
@Tim Robinson - got it now, 10x!
akapulko2020
Arrggh, now realized the question is not phrased correctly. Will edit now, please view again.
akapulko2020
+3  A: 
Process p = ...

bool exited = p.WaitForExit(10000); // 10 seconds timeout
Thomas Levesque
+1  A: 

In fact, you can use Process.WaitForExit().

Simply get the process to wait for via

Process p = Process.GetProcessById(iYourID);

And then call

if(!p.WaitForExit(iYourInterval))
{ 
    p.Kill();
}

Edit:

You can also get processes via their name by Process.GetProcesses(strYourProcessName);

Emiswelt
Cool! Now, if I can this to work on remote machine, this is just what needed (since I need to kill a whole bunch of processes with the same exe name) Thanks!
akapulko2020