Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop process in C#, knowing its filename?

I have a programm that runs another one (lets call the first app Stater and the second app - Worker).

I use

process.start();
process.waiForExit();
process.Close();

in Starter.

But if Starter is forced to close while waiting for Worker (for some extern reason) Worker will be still in processes, blocking files, eating memory etc.

So, I want to check if Worker is already running before I will try to start it. I've tried Process.GetProcessesByName("worker.exe") but no luck (even if I can see Worker in Task Manager).

I've seen some topics here about checking every process in memory for its modules, but still I already know the running file I hope to avoid such solution.

Any advices?

like image 669
Pavel Oganesyan Avatar asked Mar 13 '12 10:03

Pavel Oganesyan


People also ask

What does kill () do in C?

The kill() function sends a signal to a process or process group specified by pid. The signal to be sent is specified by sig and is either 0 or one of the signals from the list in the <sys/signal. h> header file. The process sending the signal must have appropriate authority to the receiving process or processes.

How do you kill a parent process?

You will know if this method will work for you, if while running your script and you press Ctrl + C would kill the parent and all spawned processes. The reason for this is the different signals that kill can send. By default kill <pid> will send 15 <SIGTERM> signal.

What is the kill system call?

The kill() system call can be used to send any signal to any process group or process. If pid is positive, then signal sig is sent to the process with the ID specified by pid. If pid equals 0, then sig is sent to every process in the process group of the calling process.

Does SIGTERM kill child process?

The SIGKILL signal can be sent with a kill system call. Note though, the SIGTERM handler registered in the following code sample can't catch the delivered SIGKILL , and it immediately kills the given child process. The following program spawns a child process and registers the SIGTERM handler in it.


1 Answers

The reason you cannot find it is because you're using .exe. If the executable shows up as worker.exe in TaskManager, just call:

Process[] workers = Process.GetProcessesByName("worker")
foreach (Process worker in workers)
{
     worker.Kill();
     worker.WaitForExit();
     worker.Dispose();
}
like image 61
Tung Avatar answered Oct 28 '22 08:10

Tung