signal when user kills process? - c++

I overloaded the 6 signals listed on this site http://www.cplusplus.com/reference/clibrary/csignal/signal.html
Then i ran my app (double click not ran through IDE) and tried 1) end task 2) X on topright and 3) kill process. I expected the first two to cause some kind of signal (i am on XP) but alas i got nothing. Am i not allowed to open files to write into when a signal occurs? i am guessing i am (SIGSEGV allowed me).
When firefox crashes or when i kill it, it remembers what pages i was. Does it log the address everytime i click a page or does it do that on a signal/crash?
my main question is what signal can i use to catch kill process

Win32 does not provide an option to intercept your program being killed with TerminateProcess (which is what will happen when you "End Task" from Task Manager or click on the [X]).
You can catch the SIGSEGV signal because the C runtime library provides an emulation of this signal when running on Windows. When your program causes a Windows access violation (exception 0xC0000005), the runtime library has the option to catch that and simulate a Unix style SIGSEGV for you. This is, however, not the best way to handle such an exception. If you are writing a Win32 program, you shouldn't generally try to use Unix style services.

You can catch runtime error like an access violation if you override the default exception handler calling SetUnhandledExceptionFilter (this is a win32 function and as such doesn't rely on C library emulation). This is the method can used to provide "minidumps" when a program crashes.
But this exception handler will not be called when you normally close your application, or when your application is closed from Task manager. In the last case windows is calling TerminateProcess, is not a clean shutdown but it is forcing your program to terminate.
I'm not aware of which is the implementation used by Firefox, but to save the current tabs open is likely to have a timer running, and each time it is run it save the history to a file and some kind of dirty mark.
Other more complex solutions to detect when a program is closed (implemented by antivirus and similar programs) is to have two unrelated programs running, each checking that the other is still running, and if one detect the other was closed the run it again.

Windows apps are either console apps or GUI apps. Console apps tend to get WM_CLOSE, console apps CTRL_CLOSE_EVENT. Neither are signals; neither would be sent if your app is ended via TerminateProcess().
If you want to store where you were, use a memory-mapped file and update that on every action. When your process exits, the dirty page in memory is written back to file by the OS, possibly at other moments too. This solution allows the OS to manage disk I/O for you, and it's in a better position to do so.

Related

How to write a Windows application that doesn't immediately release control to the calling application

I am writing a small application (.exe) that does some tasks and then returns an exit status. It is meant to be run regularly from another application (which I have no control over) that uses the status code to determine further action.
It works just fine if I compile and link it as a console app. However, that makes the console window flash briefly on the screen every time it is run, which is a little bit annoying. I tried to make it a Windows app, but the problem then is that Windows releases control to the calling application (or the OS) immediately after start. Thus, any exit status my application generates is returned too late and is never seen by the calling application.
Is there a way to force my app to stay in the foreground, so to speak, and not release control before it actually exits? I tried to force the entry point to be the "main" function instead of "WinMain", but that didn't help.
It isn't a question of whether the child "releases control" or not - Windows is a preemptive multitasking operating system, so all processes run at once. If the parent process waits for the child to exit, it is because the programmer told it to wait for the child to exit.
It isn't easy to make a program wait for console programs but not non-console programs. The command shell (cmd.exe) works this way when run interactively, but there isn't any API that does this as far as I know. Assuming that it isn't deliberate - which would be very strange in this context - the only explanation I can think of is that the program is running an interactive command shell and feeding in your command via standard input. That's the wrong thing to do, but I have seen people trying to do it that way before.
Presumably you can choose the command line that the parent executes. Try this:
start /wait myapp.exe
(That's how you would do it in an interactive command shell.)
If that doesn't work, you may have to consult the author of the parent process for advice.

Intercept signal / event when 'Stop Debugging' button is pressed in Visual Studio

Background: I am writing a QA automation platform for an API which outputs formatted results to a specified directory. In addition, I have developed a GUI application for analyzing these results. A user may run the second application trying to analyze test results while our automated build system is running the first application modifying / generating new test data. To avoid thrashing, I have each application acquire file locks when making modifications, and releasing them when they are done. Upon normal program termination, if the running application has acquired a lock on the data directory it is released.
Problem: I need to be able to release the aforementioned file locks when either tool exists prematurely (user pressing CTRL-C, user stopping the application in debugger, or due to buggy API / application logic being tested). To handle this, I have implemented a signal handler using sigaction which handles intercepting fatal signals (tested and working), and have implemented a ctrl-c handler via the Win32 function SetConsoleCtrlHandler. However, I cannot seem to find a way to intercept the event of a user pressing the Stop Debugging button in Visual Studio. I assume this event generates something like SIGKILL / SIGSTOP (which cannot be handled through sigaction) but I would also hope there is some std library or Win32 functionality to intercept this event and perform some cleanup. Do you guys know of a way to handle this event or even what exactly this button does to kill a running application?
If you're using boost, you can use boost::interprocess::windows_shared_memory.
It is guaranteed to be released when the process ends.
Boost is just a neat wrapper around the windows API in this case. It wraps the Windows Named Shared Memory API.

Can I really not clean up when Visual Studio stops debugging?

I have a console application that runs some temperamental hardware. If I don't detach from it nicely, windows tends to bluescreen five minutes later. I can catch when the application is closed by using SetConsoleCtrlHandler. But when I hit 'stop debugging' in visual studio, it skips this process and just kills the program brutally. As of 2009 it appears nobody has a solution for this problem.
Is this still the case? Do I really have to live with a bluescreen if I accidentally hit the wrong button?
Killing the process is what that button is for. If you want the program to terminate gracefully, you need to let it run to completion. You can use the debugger's "continue" button, or just detach from the process, and then quit the program in the normal way. Or you can use the debugger to do something that makes the program quit itself, such as setting a "done" flag that controls a main loop.
You might consider splitting your program into two parts: a service that deals with the hardware's peculiarities and presents a "clean" interface to the console application, and the console application which talks to the service instead of directly to the hardware.
You immediate problem is the TerminateProcess function that even Task Manager can execute which gives you no recourse to shutdown cleanly. Even if you could solve the Visual Studio problem, someone could right click and "End Process" and you be in the same boat.
Your root problem is poorly-written device drivers. These driver should not blue-screen even if you are abruptly terminated. If you have choice but to use them then you can try to bulletproof your process by running with administrative privileges, running as a service, or confining operations to short windows of time. Or you can simply train your operators not to do the things that will cause your delicate system to blow up. And hope.

Check if windows shell has finished loading startup programs

How can i programatically check if the windows shell (explorer) has loaded all startup programs & the user login process is over ?
There is a somewhat documented event you can wait for, but it is signaled when explorer has started loading. On XP this event is called "msgina: ShellReadyEvent" and "ShellDesktopSwitchEvent" on Vista. I linked to the sources of some alternative shells in a post related to this event.
Another alternative would be to listen for the Taskbar Creation Notification message. It can fire more than once so you would need to keep track of that.
On Vista+ there is one last alternative that might just work: Programs set to run at startup are part of a job object so they cannot run at high priority. If your program runs at startup you could maybe check for this, either by using IsProcessInJob or SetPriorityClass+GetPriorityClass in a loop. (SetPriorityClass will lie about its return value IIRC)

Getting rid of the evil delay caused by ShellExecute

This is something that's been bothering me a while and there just has to be a solution to this. Every time I call ShellExecute to open an external file (be it a document, executable or a URL) this causes a very long lockup in my program before ShellExecute spawns the new process and returns. Does anyone know how to solve or work around this?
EDIT: And as the tags might indicate, this is on Win32 using C++.
I don't know what is causing it, but Mark Russinovich (of sysinternal's fame) has a really great blog where he explains how to debug these kinds of things. A good one to look at for you would be The Case of the Delayed Windows Vista File Open Dialogs, where he debugged a similar issue using only process explorer (it turned out to be a problem accessing the domain). You can of course do similar things using a regular windows debugger.
You problem is probably not the same as his, but using these techniques may help you get closer to the source of the problem. I suggest invoking the CreateProcess call and then capturing a few stack traces and seeing where it appears to be hung.
The Case of the Process Startup Delays might be even more relevant for you.
Are you multithreaded?
I've seen issues with opening files with ShellExecute. Not executables, but files associated an application - usually MS Office. Applications that used DDE to open their files did some of broadcast of a message to all threads in all (well, I don't know if it was all...) programs. Since I wasn't pumping messages in worker threads in my application I'd hang the shell (and the opening of the file) for some time. It eventually timed out waiting for me to process the message and the application would launch and open the file.
I recall using PeekMessage in a loop to just remove messages in the queue for that worker thread. I always assumed there was a way to avoid this in another way, maybe create the thread differently as to never be the target of messages?
Update
It must have not just been any thread that was doing this but one servicing a window. Raymond (link 1) knows all (link 2). I bet either CoInitialize (single threaded apartment) or something in MFC created a hidden window for the thread.