killing a process from task manager does not fire console CTRL_CLOSE_EVENT

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • shiry

    #1

    killing a process from task manager does not fire console CTRL_CLOSE_EVENT

    Hi,
    I need to do some important cleanup before my console application
    exists. I used the console ctrl event. This is working well and it
    fires for all cases, including the CTRL_CLOSE_EVEN T (if I close the
    application from the X botton). But on
    the contrary to what the MSDN indicates
    (ms-help://MS.VSCC.2003/MS.MSDNQTR.2003 OCT.1033/dllproc/base/handlerroutine. htm),
    ending my process from the task manager did not fire the
    CTRL_CLOSE_EVEN T.
    I also tried to use the Appdomain processexit, which didn't work for
    any of the cases.
    This is the code as I tried it:
    public enum ConsoleEvent
    {
    CTRL_C = 0,
    CTRL_BREAK,
    CTRL_CLOSE,
    CTRL_LOGOFF = 5,
    CTRL_SHUTDOWN
    }
    public delegate void ControlEventHan dler(ConsoleEve nt
    consoleEvent);
    public event ControlEventHan dler ControlEvent;
    ControlEventHan dler eventHandler;
    public ConsoleCtrlEven tsSetup()
    {
    // save this to a private var so the GC doesn't
    collect it...
    eventHandler = new
    ControlEventHan dler(Handler);
    SetConsoleCtrlH andler(eventHan dler, true);
    }
    ~ConsoleCtrlEve ntsSetup()
    {
    Dispose(false);
    }
    public void Dispose()
    {
    Dispose(true);
    }
    void Dispose(bool disposing)
    {
    if (disposing)
    {
    GC.SuppressFina lize(this);
    }
    if (eventHandler != null)
    {
    SetConsoleCtrlH andler(eventHan dler,
    false);
    eventHandler = null;
    }
    }
    private void Handler(Console Event consoleEvent)
    {
    if (ControlEvent != null)
    ControlEvent(co nsoleEvent);
    }
    [DllImport("kern el32.dll")]
    static extern bool
    SetConsoleCtrlH andler(ControlE ventHandler e, bool
    add);
    }
    class CrashHandler
    {
    public static void
    MyProcessExitHa ndler(ConsoleCt rlEventsSetup.C onsoleEvent consoleEvent)
    {
    StopAllMotions( );
    }
    public static void StopAllMotions ()
    {
    StreamWriter y =
    File.AppendText (@"c:\temp\test .txt");
    y.WriteLine("st opping all motions");
    y.Flush();
    y.Close();
    }
    }
    public static void Main()
    {
    ConsoleCtrlEven tsSetup cc = new
    ConsoleCtrlEven tsSetup();
    cc.ControlEvent += new
    ConsoleCtrlEven tsSetup.Control EventHandler(My ProcessExitHand ler);
    Console.WriteLi ne("Press any key to exit");
    }
    Any ideas?
    Thanks.

  • Stoitcho Goutsev \(100\) [C# MVP]

    #2
    Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T

    shiry,

    Task Manager provides two ways of ending a process - from the *Applications*
    tab clicking on the *End Task* button and from the *Processes* tab clicking
    on the *End Process* button.

    The *End Task* button is the one that MSDN referes to. The ctrl event should
    fire in this case.

    I doubt it that you'll get the event if one clicks on the *End Process*
    button, though. It even warns you when you do that.
    Ending a process with this button is abnormal termination.


    --

    Stoitcho Goutsev (100) [C# MVP]

    "shiry" <shiryb@gmail.c om> wrote in message
    news:1135175611 .313160.64410@f 14g2000cwb.goog legroups.com...[color=blue]
    > Hi,
    > I need to do some important cleanup before my console application
    > exists. I used the console ctrl event. This is working well and it
    > fires for all cases, including the CTRL_CLOSE_EVEN T (if I close the
    > application from the X botton). But on
    > the contrary to what the MSDN indicates
    > (ms-help://MS.VSCC.2003/MS.MSDNQTR.2003 OCT.1033/dllproc/base/handlerroutine. htm),
    > ending my process from the task manager did not fire the
    > CTRL_CLOSE_EVEN T.
    > I also tried to use the Appdomain processexit, which didn't work for
    > any of the cases.
    > This is the code as I tried it:
    > public enum ConsoleEvent
    > {
    > CTRL_C = 0,
    > CTRL_BREAK,
    > CTRL_CLOSE,
    > CTRL_LOGOFF = 5,
    > CTRL_SHUTDOWN
    > }
    > public delegate void ControlEventHan dler(ConsoleEve nt
    > consoleEvent);
    > public event ControlEventHan dler ControlEvent;
    > ControlEventHan dler eventHandler;
    > public ConsoleCtrlEven tsSetup()
    > {
    > // save this to a private var so the GC doesn't
    > collect it...
    > eventHandler = new
    > ControlEventHan dler(Handler);
    > SetConsoleCtrlH andler(eventHan dler, true);
    > }
    > ~ConsoleCtrlEve ntsSetup()
    > {
    > Dispose(false);
    > }
    > public void Dispose()
    > {
    > Dispose(true);
    > }
    > void Dispose(bool disposing)
    > {
    > if (disposing)
    > {
    > GC.SuppressFina lize(this);
    > }
    > if (eventHandler != null)
    > {
    > SetConsoleCtrlH andler(eventHan dler,
    > false);
    > eventHandler = null;
    > }
    > }
    > private void Handler(Console Event consoleEvent)
    > {
    > if (ControlEvent != null)
    > ControlEvent(co nsoleEvent);
    > }
    > [DllImport("kern el32.dll")]
    > static extern bool
    > SetConsoleCtrlH andler(ControlE ventHandler e, bool
    > add);
    > }
    > class CrashHandler
    > {
    > public static void
    > MyProcessExitHa ndler(ConsoleCt rlEventsSetup.C onsoleEvent consoleEvent)
    > {
    > StopAllMotions( );
    > }
    > public static void StopAllMotions ()
    > {
    > StreamWriter y =
    > File.AppendText (@"c:\temp\test .txt");
    > y.WriteLine("st opping all motions");
    > y.Flush();
    > y.Close();
    > }
    > }
    > public static void Main()
    > {
    > ConsoleCtrlEven tsSetup cc = new
    > ConsoleCtrlEven tsSetup();
    > cc.ControlEvent += new
    > ConsoleCtrlEven tsSetup.Control EventHandler(My ProcessExitHand ler);
    > Console.WriteLi ne("Press any key to exit");
    > }
    > Any ideas?
    > Thanks.
    >[/color]


    Comment

    • shiry

      #3
      Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T

      Thanks,
      So, that means that I cannot catch an Application crash in this manner?
      What about AppDomain.Curre ntDomain.Proces sExit function, can it help me
      in case of a crash?
      I read somewhere that the only way to catch a crash, in order to do
      some cleanup, is to run a watcher application that uses the
      System.Diagnost ics.Process class, and get the return code of the
      application. Is that correct? Is there any other way of doing this?

      Comment

      • Willy Denoyette [MVP]

        #4
        Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T


        "shiry" <shiryb@gmail.c om> wrote in message
        news:1135237475 .581835.124160@ g14g2000cwa.goo glegroups.com.. .[color=blue]
        > Thanks,
        > So, that means that I cannot catch an Application crash in this manner?
        > What about AppDomain.Curre ntDomain.Proces sExit function, can it help me
        > in case of a crash?
        > I read somewhere that the only way to catch a crash, in order to do
        > some cleanup, is to run a watcher application that uses the
        > System.Diagnost ics.Process class, and get the return code of the
        > application. Is that correct? Is there any other way of doing this?
        >[/color]

        Killing a process is not an application crash isn't it?
        When killing a process (from process explorer or whatever), the OS removes
        the process cold, nothing is signaled because you are not supposed to kill a
        process, unless it is no longer "functional ", that is, it's no longer
        runnable/responding, and because of this the OS sees no reason to signal the
        process that it's going to be killed.
        If you need to handle application crashes, you'll have to install a catch
        handler.
        Willy.


        Comment

        • shiry

          #5
          Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T

          What do you mean by: "install a catch handler"?
          (I'm pretty new to all this programming business, so excuse me for my
          novice questions)

          Comment

          • Justin Creasy

            #6
            Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T

            If you just need to do some cleanup, you can tie into the Process
            Exited event. To do this you would have to have a watcher function like
            you mentioned. All you would have to do is find your applications
            Process object and use the following code.

            Process currentProc = <your process, many ways to get this>;
            currentProc.Exi ted += new EventHandler(pr ocessExited);

            void processExited(o bject sender, EventArgs e)
            {
            //your clean up code goes here
            }

            Hope this helps

            Comment

            • Stoitcho Goutsev \(100\) [C# MVP]

              #7
              Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T

              Just make sure you set process.EnableR aisingEvents to *true* otherwise the
              exit event won't fire.


              --

              Stoitcho Goutsev (100) [C# MVP]

              "Justin Creasy" <justin.creasy@ gmail.com> wrote in message
              news:1135260866 .473769.144100@ f14g2000cwb.goo glegroups.com.. .[color=blue]
              > If you just need to do some cleanup, you can tie into the Process
              > Exited event. To do this you would have to have a watcher function like
              > you mentioned. All you would have to do is find your applications
              > Process object and use the following code.
              >
              > Process currentProc = <your process, many ways to get this>;
              > currentProc.Exi ted += new EventHandler(pr ocessExited);
              >
              > void processExited(o bject sender, EventArgs e)
              > {
              > //your clean up code goes here
              > }
              >
              > Hope this helps
              >[/color]


              Comment

              • Justin Creasy

                #8
                Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T

                Good call Stoitcho, I can't believe I forgot to mention that seeing as
                I spent probably around 2 hours trying to find out why my event wasn't
                firing and that was the answer. Thanks for catching that!

                Comment

                • Willy Denoyette [MVP]

                  #9
                  Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T


                  "Justin Creasy" <justin.creasy@ gmail.com> wrote in message
                  news:1135260866 .473769.144100@ f14g2000cwb.goo glegroups.com.. .[color=blue]
                  > If you just need to do some cleanup, you can tie into the Process
                  > Exited event. To do this you would have to have a watcher function like
                  > you mentioned. All you would have to do is find your applications
                  > Process object and use the following code.
                  >
                  > Process currentProc = <your process, many ways to get this>;
                  > currentProc.Exi ted += new EventHandler(pr ocessExited);
                  >
                  > void processExited(o bject sender, EventArgs e)
                  > {
                  > //your clean up code goes here
                  > }
                  >
                  > Hope this helps
                  >[/color]

                  This doesn't work for our own process (CurrentProcess ), it only works for
                  process spawned from this process.
                  So there is nothing you can do in your handler other than accessing some of
                  the process properties like ExitCode, ExitTime ....
                  The reason for this is that the event is raised by the OS to the parent of
                  the process after the process has terminated.

                  Willy.


                  Comment

                  • Willy Denoyette [MVP]

                    #10
                    Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T


                    "shiry" <shiryb@gmail.c om> wrote in message
                    news:1135250894 .371967.225920@ g44g2000cwa.goo glegroups.com.. .[color=blue]
                    > What do you mean by: "install a catch handler"?
                    > (I'm pretty new to all this programming business, so excuse me for my
                    > novice questions)
                    >[/color]

                    Something like this for a console program, will catch unhandled
                    exceptions...

                    public static void DoSomethingNast y()
                    {
                    int x=0,y=1;
                    Console.Write(( y/x).ToString()); // this will throw a "devide by zero"
                    exception
                    }
                    static void Main(string[] args)
                    {

                    AppDomain.Curre ntDomain.Unhand ledException += new
                    UnhandledExcept ionEventHandler (GenericErrorHa ndler);
                    // Start a thread and do something bad...
                    Thread t = new Thread(new ThreadStart(DoS omethingNasty)) ;
                    t.Start();
                    t.Join();
                    }
                    static void GenericErrorHan dler(object sender,Unhandle dExceptionEvent Args
                    e)
                    {
                    Console.WriteLi ne("Exiting..." );
                    System.Environm ent.Exit(1); // terminate process and return error code
                    1 to parent process
                    }


                    Note that this doesn't catch process terminated by a "Kill" command!!!

                    Willy.


                    Comment

                    • shiry

                      #11
                      Re: killing a process from task manager does not fire console CTRL_CLOSE_EVEN T

                      Thanks guys.
                      You've helped me a lot!

                      Comment

                      Working...