"Gracefully" killing a process

17,892

Solution 1

If the process has a windows interface (as you refer to the red "X"), you can try Process.CloseMainWindow(). If it fails, you can fallback to Process.Kill().

Solution 2

Killing can not be graceful, perhaps you can signal the process to commit suicide. For signaling you have many options.

  • SendMessage
  • NamedPipes
  • Named Mutex
  • Sockets

Solution 3

It would depend on the process you're killing. As stated at on the relevant page for Process.Kill, "Kill is the only way to terminate processes that do not have graphical interfaces." If there is a graphical window, then go with the answer by lc above; Process.CloseMainWindow functions as the red X you referred to.

Share:
17,892

Related videos on Youtube

Icemanind
Author by

Icemanind

I am a .NET developer. I am proficient in C# and I use ASP.Net Core, Winforms and WPF. I also dabble in React and Xamarin.

Updated on August 05, 2020

Comments

  • Icemanind
    Icemanind over 3 years

    Right now I am using Process.Kill() to kill a process. Is there a way though, instead of just killing it immediately, that I can like send a message to the process instructing it to close so that it can gracefully clean up and shut down. Basically, I'm looking for the equivlent to just clicking the red X in the upper right hand corner, which I believe DOES send a message to the application requesting a shut down.

    • David
      David over 13 years
      This has been asked, and an answer has been accepted here: stackoverflow.com/questions/2055753/…
    • lc.
      lc. over 13 years
      @David Stratton Good find and yes the idea is the same, but this question is specifically asking about managed code (see tags [c#] and [.net]), which there is not yet an answer for on the other question
    • Oded
      Oded over 13 years
      @David Stratton - This question is about graceful shutdown using managed code with C#, the link you put up is about win32 and the answers require pInvokes. Not the same at all.
    • Icemanind
      Icemanind over 13 years
      @David Stratton Ic is right. I was looking for a managed C# way to do this. He answered my question perfectly.
    • David
      David over 13 years
      Ah, sorry.. My thought process was... This will work from .Net code using PInvoke.., You can call any Win32 API function from .Net using PInvoke. However, I understand if you're looking for "Pure" managed code.
  • jeff
    jeff over 6 years
    nice and simple.
  • SJ10
    SJ10 almost 6 years
    Is it possible to run something like this from shell? I have a very long process that i may need to shut down some of the way through.