Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting and stopping a process in C# .NET

Tags:

c#

.net

process

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?

like image 891
Magnus Jensen Avatar asked Sep 06 '11 15:09

Magnus Jensen


People also ask

How do I stop a process from starting in C#?

You don't really need a StopProc() method, you can just write proc. Kill() directly.

What command is used to terminate a process?

There are two commands used to kill a process: kill – Kill a process by ID. killall – Kill a process by name.

What is the difference between killing a process and stopping a process?

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.


3 Answers

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();
    }
like image 89
Amir Avatar answered Sep 19 '22 21:09

Amir


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.

like image 25
Justin Avatar answered Sep 21 '22 21:09

Justin


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.

like image 25
David Heffernan Avatar answered Sep 21 '22 21:09

David Heffernan