How to tell when my Windows app is being terminated? - c

Is there any way my Windows program (C/C++) can receive a notification when it is being killed from Taskmgr.exe? It does not appear to receive any special Windows Messages - it just terminates.
I don't want to stop it from terminating, I just want to write a notification of some kind that it was manually terminated.
Thanks.

If it's a full windows app, you should get WM_QUIT in your message pump right before the application quits.
As MSDN states: http://msdn.microsoft.com/en-us/library/windows/desktop/ms632641(v=vs.85).aspx
This isn't posted to a window's message queue, you can only retrieve it in your main message pump.
This is only when it quits cleanly. If the process is killed, this never happens.
A way you can detect it being killed on next launch, is to have a file be created on start-up and destroyed on shutdown, If the file still exists on the next start up you know that the process was killed, but not whether it was killed due to an error or because it was killed at a users request.

If you need to know immediately when your process is killed the only way I know of is to use another process as a watchdog. If you use OpenProcess() to get a handle to the process in question, you can wait on that handle (via WaitForSingleObject or similar), and the handle will be signalled when the process terminates. You'll need to do some coordination with the target process in order to track whether the shutdown was clean or forcible.

Related

debugging a running daemon with GDB

I want to debug a running daemon with the GDB. I have the process id of respective process. I typed : gdb attach process id info threads
I am getting the list of threads. * one is the current one running thread (correct me if I am wrong)
Now I am sending :
systemctl kill daemonname (this command I am running on some other terminal)
now I want to check that after hitting this command which thread is getting run.
since my daemon is getting stuck. it is not killing properly. I tried with the service-name status command. Since it is getting stuck after the above " servicename status " command. I want to trace the last thread that is getting stuck since my daemon is still not killed but running the command for checking the status of that daemon is stucked, no output is coming on output. while it should show that the service is not running or command not found if it gets killed properly.
Please help me.. i am new
I tried with the service-name status command.
You may be holding it wrong.
After you execute systemctl kill daemonname, you want to attach GDB to the process and see where it is stuck (use thread apply all where).
You will likely see that your threads are deadlocked (e.g. thread T1 is waiting for mutex A, which is held by thread T2; thread T2 is waiting for mutex B, held by thread T1).
I want to trace the last thread that is getting stuck
In general, tracing multithreaded processes is a fools errand, because the fact that you are tracing the process changes the execution environment and often causes it to no longer match execution without tracing.
Instead you should think about invariants, and make sure they are not violated.

Restarting inetd should effect instances of all inetd controlled processes

When I am sending HUP signal to inetd so that it rereads the new inetd.conf file, what I want is, the processes controlled by the inetd process should also restart, so that it can read the new command line parameters added to the inetd.conf file as part of the change.
I know I can search for the running process and kill it, but is there a standard way to do this. I could not find anything over the Internet.
The standard inetd included in NetBSD does not manage the processes it starts (except for single-threaded services, i.e. those with "wait" flags) -- it just starts them. Each child process services one active connection and then exits when done (i.e. when the connection is closed). In the general case it would be very unwise to kill such processes early without very good reason -- for example consider the case where your current login session (where you tell inetd to reload) was opened to a service controlled by inetd (e.g. sshd).
If you really want to kill processes handling active current connections then you will have to write some helper script of your own to do that, though perhaps pkill will suffice.

Linux automatically restarting application on crash - Daemons

I have an system running embedded linux and it is critical that it runs continuously. Basically it is a process for communicating to sensors and relaying that data to database and web client.
If a crash occurs, how do I restart the application automatically?
Also, there are several threads doing polling(eg sockets & uart communications). How do I ensure none of the threads get hung up or exit unexpectedly? Is there an easy to use watchdog that is threading friendly?
You can seamlessly restart your process as it dies with fork and waitpid as described in this answer. It does not cost any significant resources, since the OS will share the memory pages.
Which leaves only the problem of detecting a hung process. You can use any of the solutions pointed out by Michael Aaron Safyan for this, but a yet easier solution would be to use the alarm syscall repeatedly, having the signal terminate the process (use sigaction accordingly). As long as you keep calling alarm (i.e. as long as your program is running) it will keep running. Once you don't, the signal will fire.
That way, no extra programs needed, and only portable POSIX stuff used.
The gist of it is:
You need to detect if the program is still running and not hung.
You need to (re)start the program if the program is not running or is hung.
There are a number of different ways to do #1, but two that come to mind are:
Listening on a UNIX domain socket, to handle status requests. An external application can then inquire as to whether the application is still ok. If it gets no response within some timeout period, then it can be assumed that the application being queried has deadlocked or is dead.
Periodically touching a file with a preselected path. An external application can look a the timestamp for the file, and if it is stale, then it can assume that the appliation is dead or deadlocked.
With respect to #2, killing the previous PID and using fork+exec to launch a new process is typical. You might also consider making your application that runs "continuously", into an application that runs once, but then use "cron" or some other application to continuously rerun that single-run application.
Unfortunately, watchdog timers and getting out of deadlock are non-trivial issues. I don't know of any generic way to do it, and the few that I've seen are pretty ugly and not 100% bug-free. However, tsan can help detect potential deadlock scenarios and other threading issues with static analysis.
You could create a CRON job to check if the process is running with start-stop-daemon from time to time.
use this script for running your application
#!/bin/bash
while ! /path/to/program #This will wait for the program to exit successfully.
do
echo “restarting” # Else it will restart.
done
you can also put this script on your /etc/init.d/ in other to start as daemon

Capturing Process Termination(Task Manager) in WPF

I have a WPF application.when the application closes i do some update/insert action in database which is mandatory for my application.But if my application is forcibly closed by killing the process in taskmanager, i am not able to do operation in database.
I am doing the updating/insertingrecords in DB in "Exit" Event in "App.xaml.cs",this event is not fired when the application is killed in taskmanager.By searching i found that if a process is killed in Process Tab of Task Manager the application closes immediately without waiting for the application to respond.
One way we can capture the process termination is by having a service running which checks this application Process.
Is there any other way to catch the process termination within the same application i.e By not having another service running to check.?
Thanks in advance..
TerminateProcess does not give your application any chance to detect termination. You need an external application/service that monitors, or better yet you need to take away the reason your users have to kill the process using Task Manager.

Cleanest way to stop a process on Win32?

While implementing an applicative server and its client-side libraries in C++, I am having trouble finding a clean and reliable way to stop client processes on server shutdown on Windows.
Assuming the server and its clients run under the same user, the requirements are:
the solution should work in the following cases:
clients may each feature either a console or a gui.
user may be unprivileged.
clients may be or become unresponsive (infinite loop, deadlock).
clients may or may not be children of the server (direct or indirect).
unless prevented by a client-side defect, clients shall be allowed the opportunity to exit cleanly (free their ressources, sync some data to disk...) and some reasonable time to do so.
all client return codes shall be made available (if possible) to the server during the shutdown procedure.
server shall wait until all clients are gone.
As of this edit, the majority of the answers below advocate the use of a shared memory (or another IPC mechanism) between the server and its clients to convey shutdown orders and client status. These solutions would work, but require that clients successfully initialize the library.
What I did not say, is that the server is also used to start the clients and in some cases other programs/scripts which don't use the client library at all. A solution that did not rely on a graceful communication between server and clients would be nicer (if possible).
Some time ago, I stumbled upon a C snippet (in the MSDN I believe) that did the following:
start a thread via CreateRemoteThread in the process to shutdown.
had that thread directly call ExitProcess.
Unfortunately now that I'm looking for it, I'm unable to find it and the search results seem to imply that this trick does not work anymore on Vista. Any expert input on this ?
If you use thread, a simple solution is to use a named system event, the thread sleeps on the event waiting for it to be signaled, the control application can signal the event when it wants the client applications to quit.
For the UI application it (the thread) can post a message to the main window, WM_ CLOSE or QUIT I forget which, in the console application it can issue a CTRL-C or if the main console code loops it can check some exit condition set by the thread.
Either way rather than finding the client applications an telling them to quit, use the OS to signal they should quit. The sleeping thread will use virtually no CPU footprint provided it uses WaitForSingleObject to sleep on.
You want some sort of IPC between clients and servers. If all clients were children, I think pipes would have been easiest; since they're not, I guess a server-operated shared-memory segment can be used to register clients, issue the shutdown command, and collect return codes posted there by clients successfully shutting down.
In this shared-memory area, clients put their process IDs, so that the server can forcefully kill any unresponsive clients (modulo server privileges), using TerminateProcess().
If you are willing to go the IPC route, make the normal communication between client and server bi-directional to let the server ask the clients to shut down. Or, failing that, have the clients poll. Or as the last resort, the clients should be instructed to exit when the make a request to server. You can let the library user register an exit callback, but the best way I know of is to simply call "exit" in the client library when the client is told to shut down. If the client gets stuck in shutdown code, the server needs to be able to work around it by ignoring that client's data structures and connection.
Use PostMessage or a named event.
Re: PostMessage -- applications other than GUIs, as well as threads other than the GUI thread, can have message loops and it's very useful for stuff like this. (In fact COM uses message loops under the hood.) I've done it before with ATL but am a little rusty with that.
If you want to be robust to malicious attacks from "bad" processes, include a private key shared by client/server as one of the parameters in the message.
The named event approach is probably simpler; use CreateEvent with a name that is a secret shared by the client/server, and have the appropriate app check the status of the event (e.g. WaitForSingleObject with a timeout of 0) within its main loop to determine whether to shut down.
That's a very general question, and there are some inconsistencies.
While it is a not 100% rule, most console applications run to completion, whereas GUI applications run until the user terminates them (And services run until stopped via the SCM). Hence, it's easier to request a GUI to close. You send them the equivalent of Alt-F4. But for a console program, you have to send them the equivalent of Ctrl-C and hope they handle it. In both cases, you simply wait. If the process sticks around, you then shoot it down (TerminateProcess) and pray that the damage is limited. But your HDD can fill up with temporary files.
GUI application in general do not have exit codes - where would they go? And a console process that is forcefully terminated by definition does not exit, so it has no exit code. So, in a server shutdown scenario, don't expect exit codes.
If you've got a debugger attached, you generally can't shutdown the process from another application. That would make it impossible for debuggers to debug exit code!

Resources