How to handle a C# console application terminating? - c#

If I have a console application, is there any way I can handle the following:
Ctrl-C (I know the answer to this. Using Console.TreatControlCAsInput and Console.CancelKeyPress)
Session termination, such as when someone logs off
Process exit, such as when someone uses the task manager to close the application.
I know that if I was writing a unix application, I would handle various signals to catch the request to close (SIGTERM from memory), but I also know I need to handle these messages pretty quickly and exit before the system does a kill -9 (SIGKILL).
But for a C# console application, I'm not sure how to do this.

Session termination, such as when someone logs off
Handle the SystemEvents.SessionEnded event.
Process exit, such as when someone uses the task manager to close the application.
If you mean, if someone kills the application from the taskbar, I dont think you can handle that.

Related

Capture .Net Console Kill or Terminate

So I have a hidden console application called Hidden.exe running.
Another application Call Killer.exe will find the process Hidden.exe or its PID, and Kills the process.
How do i programmatically capture a kill command or a terminate from Task Manager? A user can browse through the process list and 'End Task' on Hidden.exe and I want to be able to capture this event and do some cleanup before it exits.
How can i do this? I have searched around, and explored alternatives from
.NET console application exit event
Send WM_CLOSE message to a process with no window
Can I send a ctrl-C (SIGINT) to an application on Windows?
etc....
But they all dont work or only work in some cases, my case is for a hidden console application and needs to somehow capture a Kill on it. None of the above solution seem to have a 'correct' solution.
There is no such answer. A kill will always work and will fire no event. This is due to security concern to prevent virus and/or malware code.
I've since found another way.

Launch Process from Windows Service

I am having one windows forms application which is designed to do specific tasks in background. Now I want to make sure that this application should be running all the time.
No one should able to close it. If some one closed it from Task Manager (Kill it) then it should restart it self.
I had couple of options for that. I have tried to make one window service which has timer and which can be check at every 1 minute that if process is not found then it will launch the process. But I have gone through couple of articles and they are saying that this is not nice idea. Is there any other way round to keeping alive my application in windows.
In my idea also if someone closes my service then also I can't detect if my WinForms application is closed or running.
What is best way to do so? I am ready to give highest privileges and I have thought that option as well that If someone kill process of my application then computer should be shut down it self.
Please share better idea to do so.
If you don't want the user closing your app, make it as difficult for him as possible:
launch it maximized
remove the frame of the window (and close, maximize,minimize buttons with it)
launch it TopMost
set ShowInTaskbar of your forms to false
ask 10 times "are you sure you want to exit???" :)
set e.Cancel to true in FormClosing event, etc...
About the Task Manager:
I think you can disable task manager altogether http://www.techulator.com/resources/3480-how-disable-task-manager-windows.aspx
Or you can hide the process (ugly and virus-like): How do I hide a process in Task Manager in C#?
Or you can sort-of make it harder to kill the process: Making an app/service such that trying to end/kill its process in Task Manager would result in "Unable to Terminate Process"
Then, if the user still manages to close your app, you can do what most people on the Internet consider a Very Bad Idea and start it from the service. As long as you are concious of the risks.
There are plenty of resource out there that tell you how to start an interactive app from the service (so evidently some people are doing it too), for example:
http://blogs.msdn.com/b/winsdk/archive/2009/07/14/launching-an-interactive-process-from-windows-service-in-windows-vista-and-later.aspx
you should know that it is impossible to prevent task manager not to close your application. and its not a proper idea to force the user.
But, if you insist I think the best way is through services with timer or thread whichever suits your solution to check its process and run it if not exists. and you didn't mention in your post that what was the reason of not using this method and why it is not a good method.
hope it helps you decide better.

Running a cleanup after a program crashes

I'm currently writing quite a simple app, but it makes a change to the OS which gets changed back when the program is closed.
The worry of course, is if the program crashes. I can do everything in my power to prevent it from crashing, or handling things if it does crash - but I can't stop someone from force closing the process (unless I can?)
Is there a way to catch that event and run just a very quick cleanup before the process exits?
I don't think there is anything you can do if your process gets killed - one approach would be to have your app spawn a helper process that is just there for this case. When your app terminates that process can detect that and "fix" the OS setting as desired before it shuts down itself - obviously this only would work if that other process doesn't get killed first.
You can hook UnhandledException. You can't stop the application terminating, but you can log or do some clean up. This allows you to handle the case of application crashes.
It terms of someone actually just killing the process there's nothing you can do about that.
Program defensively.
Write the original settings to a file. Delete the file when closing. When starting, check whether the file is there - if it is, your process was killed and you know what to return the settings to.
Programming 201 - the basics of transactions, applied to system settings wit hthe program runtime as transaction boundary.
If you don't mind a little interop to C or C++ code, and if you're running on Windows Vista or newer, you could make use of the Application Recovery and Restart APIs. These APIs tell Windows to intercept your process when something catastrophic happens, so that you can perhaps call a little cleanup code before Windows kills the process completely.
See http://msdn.microsoft.com/en-us/library/cc948909.aspx.

Handling a forced exit

Is there any good way to handle a forced exit in C#?
I have a formless C# application that talks to an LCD over serial. Once the application is running, the only way to kill it is with task manager. The trouble with this is that the program needs to turn the LCD off when it is done, and it doesn't look as if my Application.ApplicationExit event is ever fired in this condition.
Any ideas?
Once the application is running, the only way to kill it is with task manager.
My big idea would be to change this.
Stick an icon in the notification area that the user can use to shut your app down properly, or set it up so that running the app again will instead shut down an already-running instance if one exists, or any other way that sounds like a good idea.
Requiring a user to use Task Manager to shut down your application screams poor design.
Write a code in your program loop (with a timer perhaps) to read a file or a registry key. For example if a file at C:\YOURPROGRAM\CLOSEME contains text "closeme", close your program gracefully. Write another program that write that C:\YOURPROGRAM\CLOSEME file. So, whenever you want to shutdown your program, don't use taskmanager, instead, open second program.
Some options:
Write a separate process with a GUI that can start and stop the main process. For example, when you install the Apache web server on Windows the server itself is installed as a service. It can be started and stopped from the system services management panel, but it also comes with a "monitor" process that sits in the notification area, tells you whether Apache is running and lets you start or stop it manually.
If it's acceptable for your use-case, make the application a console application. You can register a handler for when the user presses CTRL+C (see Console.CancelKeyPress) that performs your cleanup before your process exits. This still won't let you handle someone killing the process from Task Manager, but it's very easy to do and might be good enough depending on your situation.

Is there a posix SIGTERM alternative on Windows? - (A gentle kill for console application)

I have a console daemon that is run by a GUI application. When the GUI application is terminated I'd like to stop the daemon as well.
How can I do it in a gentle way on windows?
On Linux, I would just use SIGTERM is there a similar mechanism on windows for console applications?
To provide a bit more detail, the daemon app is written in python and the gui is written in C# & windows forms.
Define "gentle" :)
I'm assuming there is already a communication mechanism in place between the daemon and the GUI. Just introduce a "quit" command and send it.
If you want to kill the daemon even if it's busy doing something (or is frozen), use TerminateProcess().
To have the best of both, you can send "quit", then wait on the process handle for some time (WaitForSingleObject()). If the daemon process does not die in, say, 5 sec, then terminate it.
If the main thread of the daemon is prone to long periods of busy activity, have the daemon start a background thread that does nothing but waits for a named event. To signal that thread, open the event by name from GUI, then raise it. It's up to the daemon what to do upon event detection, but at least it will be a controlled shutdown.
Windows doesn't have signals in the way you're thinking.
There's some infrastructure for changing how the (faked) SIGTERM and SIGBREAK are handled by console apps, mostly SetConsoleCtrlHandler and GenerateConsoleCtrlEvent but both are only of use in the console application itself; not from outside.
It's worth noting that all a windows console app does when it receives a SIGTERM is call ExitProcess, nothing special. I'm not 100% on what the python equivalent is called, but whatever standard "exit" call should be equivalent.
I'd suggest writing some code to signal the console app, causing it to call ExitProcess itself. If that's not an option, use TerminateProcess (equivalent Process.Kill) to close the console process from the outside; attempting to "fake" an ExitProcess is dangerous for reasons noted in the MSDN article.

Categories

Resources