I am trying towrite a simple program that has two methods, one that starts a process and one that takes down the same process. as in:
public Process StartProc(string procname)
{
Process proc = new Process();
proc.StartInfo.FileName = procname;
proc.Start();
return proc;
}
public void StopProc(Process proc)
{
proc.Close();
}
Is it possible to do this like that?
You don't really need a StopProc() method, you can just write proc. Kill() directly.
There are two commands used to kill a process: kill – Kill a process by ID. killall – Kill a process by name.
A process can be suspended by sending it the STOP signal, and resumed by sending it the CONT signal. To kill a process means to cause it to die. This can be done by sending it a signal. There are various different signal, and they don't all cause the process to die.
By starting the process, you can get the unique Id of that process and then you can kill it like this:
public static int Start(string processName)
{
var process =
Process.Start(processName);
return
process.Id;
}
public static void Stop(int processId)
{
var process =
Process.GetProcessById(processId);
process.Kill();
}
Yes, the method you are after is called Kill
, not Close
:
public void StopProc(Process proc)
{
proc.Kill();
}
This will forcibly close the process - when possible it is preferable to signal the application to close such as by requesting that the application close the main window:
public void StopProc(Process proc)
{
proc.CloseMainWindow();
}
This allows the application to perform clean-up logic (such as saving files), however may allow the process to continue running if it chooses to ignore the request and will do nothing if the process does not have a main window (for example with a console application).
For more information see the documentation on the Process.CloseMainWindow
method.
I think you are looking for Process.Kill()
.
You don't really need a StopProc()
method, you can just write proc.Kill()
directly.
However, it is not generally recommended that you terminate processes in such a brutal way. Doing so can leave shared objects in an undefined state. If you can find a way to co-operatively close the process that is to be preferred.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With