C++ program exited with code 0 error - c++

I'm doing c++ at my job for the first time in years and am trying to track down a problem. I wrote code that goes out and enumerates the processes running on a machine and returns performance metrics. My problem is that some sort of unhandled error occurs and in the debug window I get a message saying the program has exited with code 0. Here is the code in the main function
int _tmain(int argc, _TCHAR* argv[])
{
while(nRun == 1)
{
try
{
WriteHeartBeat();
DoProcessLoop(dwTotalRAM, nCheckPause, oPMeter, cFileName, oProcess, oCPUUsage, nProcCount, ddsCaps2, lpDD);
CopyPerfFileToDest(cFileName);
nRun = 1;
tEnd = time(NULL);
}catch(...){
AddToLog("Error in Main Function");
}
}
AddToLog("App Stopped");
return 0;
}
The program runs for a long time but after a while it just comes back saying it exited with code 0 but that "App Stopped" line is never printed into the log. Does anyone know what kind of error I could have or what issue could be occuring? Is that try catch block sufficient enough to catch any error that could occur or is there something else I could do. Any help you could offer would be really appreciated.
EDIT: The log file should get 3 entries from here if it exits correctly. They are "Doing Process Loop" for the the "DoProcessLoop" Function, "Copying File" for the "CopyPerfFileToDest" function and the "App Stopped" if it stops correctly. When I make it stop correctly myself I get all 3 lines, when it is stopping incorrectly I only get "Doing Process Loop" in the log and then it exits with code 0. The error must be in there. I was curious if there is a generic error trap I can do to catch any all errors.

This can happen if one of functions called from _tmain called exit(0):
http://www.cplusplus.com/reference/clibrary/cstdlib/exit/
http://msdn.microsoft.com/en-us/library/6wdz5232.aspx

Sometimes files are not flushed right so if the AddToLog function defers writing to a file right before exit then it might not write out the value. You can debug the program to see if something strange is happening, or add a variable like status and set it in your catch function then return it at the end, so you know based on the value if there was an error.

Try changing the return of addtolog with a boolean and surrounding add to log with:
boolean logged=false;
while(!logged){
logged = AddToLog("App Stopped");
}
This should prevent the program from exiting until "App Stopped" is written, which may be the problem.

Related

C++ What exactly does exit() do when using multiple threads?

I'm working on some code that uses an existing code-base which is now a DLL. What I'm trying to do it to terminate all the threads that are were started, but keep my main program running.
This is the basic structure of the code:
void Mainprogram()
{
tempProcessingThreadHandle = (HMODULE)_beginthread(SomeDLLEntry, 0, (void)&Params); //SomeDLLEntry is a function in some.dll
//Other Code I Want to Run
}
In the DLL:
void SomeDLLEntry()
{
tempProcessingThreadHandle = (HMODULE)_beginthread(SomeOtherDLLThing1, 0, (void)&Params);
tempProcessingThreadHandle = (HMODULE)_beginthread(SomeOtherDLLThing2, 0, (void)&Params);
if (someCondition)
return;
}
void SomeOtherDLLThing1()
{
if (someOtherCondition)
exit(1);
}
I thought that returning from SomeDLLEntry() would cause the threads started in the DLL (SomeOtherDLLThing1 and 2) to terminate as well, but that's not the case, as seen in the debugger; SomeDLLEntry() thread would disappear, but the others are still running.
Now, if I set someOtherCondition to true, and exit(1) is called from SomeOtherDLLThing1(), what should happen? When I debug over this, the debugger seems to crash, but it appears to go past the exit(1) line and give me:
Unhandled exception at 0x6B4E87CD (Mso20win32client.dll) in Mainprogram.exe: 0xC0000005: Access violation reading location 0x0000018C.
Is this because the whole process (including Mainprogram()) has been terminated? What exactly does calling exit(1) in SomeOtherDLLThing1() do? How can I properly terminate all of the DLL-related threads and continue with my Mainprogram()?
The only way to safely terminate threads and continue to execute is to coordinate with those threads, have them cleanly finish, then join the thread handles.
There is no free lunch.
Other choices are "hack, force halt of threads, and pray you get lucky" or "do your work in another process, and pray summary shutdown causes no problems".

How to get CLion to show exceptions?

I have CLion installed with presumably default configuration. I think something is wrong with it, because I can't see exceptions. For example, this code:
int main(){ throw 5; }
Prints only Process finished with exit code 0
Why doesn't it print the exception?
Why does it print 0 instead of 1?
For comparison:
int main(){try { throw 5; } catch(int x) { std::cout << x << '\n'; }}
This prints 5, so it looks like code is correctly run and the exception is correctly thrown. It's just hidden by CLion somehow.
Edit: This is not a duplicate of "not seeing any console output". I made extremely clear in my question that I was indeed seeing console output for prints. My issue concerns exceptions specifically, not console output generally.
In your first piece of code you have not caught the exception, so it is handled by the default handler. You therefore have no control over the return code from the executable. Operation is as expected.
If you would like CLion to display the exception you can configure it to do so. Note that this will only apply when CLion is debugging your executable, outside of CLion your executable will continue to behave as you have already seen.
Go to run then view breakpoints.
Go to exception breakpoints and when any is thrown.
To display the stack trace when the exception is thrown check stack trace
If you would like your program to stop for your intervention, check enabled and when thrown.
Make sure to use Run/Debug and not Run/Run to launch your program.

Program doesn't stop after returning 0 from main

I wrote a program that encodes files with Huffman coding. It works fine but for some reason after returning 0 from main function it doesn't stop.
Main function looks like:
int main(int argc, char *argv[])
{
if (argc < 5)
{
std::cout << "..." << std::endl;
}
else
{
if (!std::strcmp(argv[1], "haff") && !std::strcmp(argv[2], "-c"))
HuffmanC(argv[3], argv[4]);
if (!std::strcmp(argv[1], "haff") && !std::strcmp(argv[2], "-d"))
HuffmanD(argv[3], argv[4]);
std::cout << "Operations: " << count << std::endl;
}
return 0;
}
When I run it, I get:
MacBook-Pro-Alex:code alex$ ./main haff -c test.txt test.haffOperations: 37371553
It ends with an empty line and terminal says that the program keeps running, but the last cout statement executes well and as I get it it should return 0 and finish. How can I make it finish after returning 0? Or is the problem in the rest of the code?
Or is the problem in the rest of the code?
Possibly. Perhaps you've corrupted your stack somehow, so that you're "returning" from main to someplace you didn't expect. We can't really know without an complete, verifiable example.
How can I make it finish after returning 0?
You can use the kill command on MacOS to terminate it forcefully. Using the GUI task manager may or may not work.
But perhaps a more effective course of action would be to attach a debugger to the process and see what it's actually doing.
You could read this explanation on how to do this on MacOS with XCode - but I don't use MacOS, so I wouldn't know. Also, #SergeyA graciously suggests trying using pstack to get the process' current stack. Of course, if the stack has been garbled, there's no telling what you'll actually get.
Make sure the application is compiled with debugging information included.
Finally - it's probably better to run the program with a debugger attached in the first place, and set a breakpoint at the last cout << line.

QCamera::start gives mysterious "failed to start" log message

It's just plain luck my program is so simple, so I eventually found out what causes the mysterious log message. My program log looks like this:
Debugging starts
failed to start
Debugging has finished
Which happens after:
camera = new QCamera(QCameraInfo::defaultCamera());
// see http://omg-it.works/how-to-grab-video-frames-directly-from-qcamera/
camera->setViewfinder(frameGrabber = new CameraFrameGrabber());
camera->start();
The start() method causes this message in console. Now the meaning of the message is obvious, what it's not very helpful. What steps should I take to troubleshoot it?
Reasons for this might differ, but in my case it was simply because I provided invalid QCameraInfo. The culprit is that QCameraInfo::defaultCamera() might return invalid value if Qt fails to detect any cameras on your system, which unfortunately happens even if cameras are present.

Make main() "uncrashable"

I want to program a daemon-manager that takes care that all daemons are running, like so (simplified pseudocode):
void watchMe(filename)
{
while (true)
{
system(filename); //freezes as long as filename runs
//oh, filename must be crashed. Nevermind, will be restarted
}
}
int main()
{
_beginThread(watchMe, "foo.exe");
_beginThread(watchMe, "bar.exe");
}
This part is already working - but now I am facing the problem that when an observed application - say foo.exe - crashes, the corresponding system-call freezes until I confirm this beautiful message box:
This makes the daemon useless.
What I think might be a solution is to make the main() of the observed programs (which I control) "uncrashable" so they are shutting down gracefully without showing this ugly message box.
Like so:
try
{
char *p = NULL;
*p = 123; //nice null pointer exception
}
catch (...)
{
cout << "Caught Exception. Terminating gracefully" << endl;
return 0;
}
But this doesn't work as it still produces this error message:
("Untreated exception ... Write access violation ...")
I've tried SetUnhandledExceptionFilter and all other stuff, but without effect.
Any help would be highly appreciated.
Greets
This seems more like a SEH exception than a C++ exception, and needs to be handled differently, try the following code:
__try
{
char *p = NULL;
*p = 123; //nice null pointer exception
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
cout << "Caught Exception. Terminating gracefully" << endl;
return 0;
}
But thats a remedy and not a cure, you might have better luck running the processes within a sandbox.
You can change the /EHsc to /EHa flag in your compiler command line (Properties/ C/C++ / Code Generation/ Enable C++ exceptions).
See this for a similar question on SO.
You can run the watched process a-synchronously, and use kernel objects to communicate with it. For instance, you can:
Create a named event.
Start the target process.
Wait on the created event
In the target process, when the crash is encountered, open the named event, and set it.
This way, your monitor will continue to run as soon as the crash is encountered in the watched process, even if the watched process has not ended yet.
BTW, you might be able to control the appearance of the first error message using drwtsn32 (or whatever is used in Win7), and I'm not sure, but the second error message might only appear in debug builds. Building in release mode might make it easier for you, though the most important thing, IMHO, is solving the cause of the crashes in the first place - which will be easier in debug builds.
I did this a long time ago (in the 90s, on NT4). I don't expect the principles to have changed.
The basic approach is once you have started the process to inject a DLL that duplicates the functionality of UnhandledExceptionFilter() from KERNEL32.DLL. Rummaging around my old code, I see that I patched GetProcAddress, LoadLibraryA, LoadLibraryW, LoadLibraryExA, LoadLibraryExW and UnhandledExceptionFilter.
The hooking of the LoadLibrary* functions dealt with making sure the patching was present for all modules. The revised GetProcAddress had provide addresses of the patched versions of the functions rather than the KERNEL32.DLL versions.
And, of course, the UnhandledExceptionFilter() replacement does what you want. For example, start a just in time debugger to take a process dump (core dumps are implemented in user mode on NT and successors) and then kill the process.
My implementation had the patched functions implemented with __declspec(naked), and dealt with all the registered by hand because the compiler can destroy the contents of some registers that callers from assembly might not expect to be destroyed.
Of course there was a bunch more detail, but that is the essential outline.