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

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.

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.

Getting debug output from a crashed VS2010 application

Question: Can I set up VS2010 so it automatically writes debug output to a file?
Motivation: I have a DirectX 9 application that I'm trying to debug. I've noticed that when my application is fullscreen, it may crash under certain conditions. Normally I would just check my logs or DirectX debug output. However, the way my program crashes prevents that. It freezes and does not respond to any my attempts to end it (including "End Process" from task manager). Moreover, it also freezes my VS2010, and so VS doesn't respond to any commands either. The only way out of this whole thing that I've found is to End VS process. This, however, also destroys the output I'd very much like to read.
Now I see two ways out of this. First is to write all the debug info to a file but I have no idea how to do it. Second is to make my application crash in a more friendly way, but this seems like a difficult task.
Probably MiniDumpWriteMiniDump(..) helps on this. You can at any time dump the current state of the process to a file. After that, you can open the dumps with Visual Studio and analyze the state of the process - this includes callstacks of every thread, variable values...
Try to identify conditions in which your process crashes and write one or more dumps.
Another try is to install the Windows Debugging Tools and use WinDbg to debug your application. This is not as comfortable as Visual Studio, but allows a deeper insight.
Edit:
If there are debug statements made with OutputDebugString(..), you can use DebugView (from Microsoft, earlier Sysinternals) to display it.

What is the Best Practice for Combating the Console Closing Issue?

After compiling console programs the console window closes immediately after running. What is the best practice for keeping it open? I've searched google loads, I'm used to codeblocks where you don't have to worry about it, but, I want to mess around with Visual Studio a bit and with VS, my console closes. All over the interwebz there are several different ways to keep it open, however, I've read that most of them are bad coding techniques. What is everyones preferred method?
When I'm using Visual Studio and I don't need debugging I just run it using Ctrl+F5 keystroke – and it prevents console from closing.
Since you always run in the debugger, set a breakpoint on the return statement from main().
The debugger is your best friend, learn (and learn early) to use it to your advantage at every opportunity.
Run your program in a console, which would be the expected way of running a console program ...
Alternatively, you can make a little batch file to execute your program that would have:
REM batch file to launch program
yourprogram.exe
PAUSE
and the PAUSE cmd.exe command will ask to user to press any key.
I tend to use system("PAUSE"); which gives you a
Press any key to continue . . .
message.
cin is grossly inelegant but easy for the forgetful to derive:
{
char c;
std::cin >> c;
}
That holds the window open until you type a character /* edit */ and hit enter.
std::cin.get() will close the window the moment you type a character, which, depending on how easily you become habituated, runs a marginally greater risk of "whoops, I wish I hadn't closed that!" than the two-keystroke operator>>(istream &).
Both differ from a system("pause") in that they return in a program-accessible way the value of the character you typed, so, if as not infrequently happens, one kludge leads to another, you can write a switch statement based on what you typed to (for example) exit immediately, write some values to a log, run it again, etc.
I use:
cin.get()
I heard it was less costly than system("PAUSE") and it works on POSIX systems too.
There's a great link that goes into detail about this.
Resist the temptation to do anything. Well behaved command line programs exit when they've finished running reporting a status via their exit code. This enables them to be scriptable and 'good citizens' in automated environments. Even in an interactive environment, why force the user to make an extra key press just because of your debugging environment?
If you run, rather than debug then Visual Studio will open a console windows that pauses after your application exits so that you can still view the output. I don't know why the behaviour is different when you debug, perhaps because you have breakpoints available so if you want to see the output at various stages you can place breakpoints after the relevant output statements, or at the end of main or enable various 'stop on exception throw' options.
Whatever the reason, I've never felt compelled to compromise the behaviour of my application just to enhance my debugging experience.
A very common one is to just put in code to read a key from the console after your main application code closes. The keystroke read in just gets thrown away, but it holds the console open.
It's not pretty, necessarily - but I often do this wrapped in a debug define, so during debugging, the console is held open. During release, I'm usually not running inside VS, and when run from a command line, this is no longer an issue.
The "don't do that" responses in this thread may seem curt, but they're fairly sensible. I happened across this question because I'm debugging a gtest suite that used to run fine, but now crashes mysteriously when launched. When run from the console, it pops up a dialog saying "blah.exe has stopped working"; but, when run from the debugger, the console pops up momentarily, vanishes, and the program exits with 0 status.
I should have been thinking about how odd this difference in behavior was, but instead I was like: "Aw, man---I gotta make that console window stay up so I can see what it says." Right?
It turns out that the machine I'm working on (a colleague of mine's) had the 'Command Arguments' for the debugger set to '--gtest_filter=*testMsg*'. I noticed this right away, too, but it never occurred to me that all the tests matching the filter had been renamed in a recent commit. So, when launched from the debugger, gtest wasn't finding any tests to run and was simply exiting. Another 90 minutes of my life I'll never get back. (-_-) I could have ditched this tar baby a lot sooner if my knee-jerk reaction hadn't been to think I needed that console window to stay open in order to solve the problem...
Call this function before you return at the end of main:
void onEnd()
{
printf("Press any key to exit...");
_getch();
}
You can specify that the executable is a Console app, not a Windows app, at least in VS2017. This makes your application run in a "Microsoft Visual Studio Debug Console", with "Press Any Key To Close This Window" appearing at the end of the console output:
Right click the project to bring up Properties.
Linker > System > Subsystem > Select "Console".
Press Apply before closing.

How to control what happens when a program is iconned in Windows XP

I have a real-time program that needs to be operating continuously. When the program is iconned, it seems that it sometimes stops updating and other times will abort when it is restored to the active state. Is there a method of controlling what happens when my program is iconned? I am using Visual Studio 2005.
I'm stealing lothar's comment and presenting it as an answer: You may want to implement your real time program as a windows service. If you need to start and stop it under user control, you can provide a GUI (that does not need to run all the time) to start, pause, continue, and stop the service. As a service, your program is much less likely to be interrupted by the user doing thing on the computer, including things like logging out.

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.