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

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.

Related

C++/WinRT GetGattServicesAsync() not responding in MFC app

C++, WinRT, VS2017 MFC, Win10
I have a C++/WinRT VS2017 console app as a test platform to find my Bluetooth LE device, enumerate the services and characteristics, and then write a value to the Tx characteristic, etc. I have all of that working and now I am trying to move that code to an existing VS2017 MFC app.
In the console app the BluetoothLEAdvertisementWatcher and callback to the watcher.Received() were done in the main.cpp. Once my BLE device was found, a separate function was called to create the device object from the deviceAddress and then enumerate the services and characteristics.
In the MFC app I created a separate function run in a separate thread to establish the watcher and attach the callback. That all works fine up to the point that it needs to GetGattServicesAsync(). In the console app the function OpenDevice() used to create the device object and get the services was done with a get() as in:
OpenDevice(deviceAddress).get();
The first thing OpenDevice() does is create the device object using
auto device = co_await BluetoothLEDevice::FromBluetoothAddressAsync(deviceAddress);
If the device object is created, then the next thing it did was get the Services with:
auto services = co_await device.GetGattServicesAsync();
Here is where my MFC code fails. In the function thread that creates the watcher and watcher.Received callback my MFC code does the same call to OpenDevice(). In OpenDevice the device object is indeed created but then the call to GetGattServicesAsync() will never finish so matter how long I wait. If I enter the GetGattServicesAsync() in Debug mode, however, then it works fine.
For testing I have also put the OpenDevice() code within the watcher thread but, again, it stalls on GetGattServicesAsync().
In this case, however, I cannot use the co_await but had to use
auto services = device.GetGattServicesAsync().get();
Regardless, the GetGattServicesAsync() never finished.
Any suggestions of what I need to do or what I am doing wrong?
Since running in Debug was working I was trying to solve why this was not working in Release mode. I was relying on my log file entries to track the progress after the fact. For the halibut I put in some Beeps() to let me hear the progress and I was hearing beeps but not seeing log entries after that GetGattServicesAsync(). Apparently what was happening is that, for what ever reason, the GetGattServicesAsync() was NULLing out the handle to my log file so no writes were taking place. I did a check for NULL after the GetGattServicesAsync() and, if it was, re-established the log file. All of a sudden my log file was showing the progress that I thought was not happening. Sometime I think it is just me...:-(

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.

Closing an application properly: an Alternative to TerminateProcess

I'm facing an issue with TerminateProcess() function.
The application I'm currently writing a JobScheduler app that schedules and launches job at a specific time.
For this purpose, I'm using CreateProcess() to execute my JobLauncher.
The JobLauncher process then launches a console program (using createprocess ) which effectively executes the job executable, waits for its termination and monitors the duration, user and kernel times elapsed etc.
In order to kill the job from the JobScheduler I firstly started using TerminateProcess() but it does not allow me to close the executable itself properly. I mean i found no way to hook any termination event.
Until I find a better way than a brutal TerminateProcess(), I wrote an intermediate solution using the GenerateConsoleCtrlEvent() in the calling program.
In the job application that launches the target job executable, I installed a handler using SetConsoleCtrlHandler().
And in the handler, I can terminate the process of the job and notifies my thirdparties properly.
This is the better solution I found for now.
Is there a better way to programmaticaly and properly close a process ?
Do you this solution is completly absurd ?
I'm not a "system-level" specialist developer though...
Z.
This well know Windows console problem and you can find some solutions here.
We used on internal console utility which has name "Kamikaze". It worked as described here and for me it's a best solution cause there is no problem with porting between Windows versions and Windows architectures (x86, x64).

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)

signal when user kills process?

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.