Program Doesn't Terminate Correctly - c++

I'm writing a computer vision app (C++ and OpenCV). I am creating a GUI for it with wxWidgets - this is very simple; a button-press event calls the tracker app to begin.
My call to terminate the app (i.e. on clicking to close button) is as follows:
// Exiting the App
void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
{
// true is to force the frame to close
Close(true);
}
This usually works with more trivial GUI apps. However, on this occasion, the frame disappears yet, in the task manager, the process seems to continue running and holding memory. It's very annoying because if I run or debug the application and later make some changes and try to run again, without manually terminating the process beforehand, the compiler throws a link error because the .exe is
not found or not built by the last incremental link.
Tried inserting a brute force exit(1); in the onQuit method but it causes the app to crash.
I'm not sure what it is.. when running without the GUI, the app runs and terminates fine (albeit it is called slightly differently - from the main() function instead of from a button-press event handler which calls an abstract base class).
Is it possible that it is because a class is being declared with global scope? As in, in one file I have an instance of a class declared outside of any class method? Perhaps wxWidgets can't handle this?
To clarify:
The frame I'm closing is a top level frame. I had no problems with the exact same GUI code when it does not call the computer vision methods.
I haven't specifically coded any multi-threading but to begin with, I was getting an error that said "Error: Cannot initialize OLE". To fix this, I had to set wxUSE_DRAG_AND_DROP, wxUSE_CLIPBOARD, wxUSE_OLE and wxUSE_OLE_AUTOMATION to 0 (instead of 1) and then (re)compile wxWidgets.
Just wondering, is there some kind of threading going on with HighGUI that is inconsistent with WxWidgets? Has anybody else encountered similar problems?

::wxExit
void wxExit()
Exits application after calling wxApp::OnExit. Should only be used in an emergency: normally the top-level frame should be deleted (after deleting all other frames) to terminate the application. See wxCloseEvent and wxApp.
Include files
<wx/app.h>
You can also simply call the crt function exit() which will instantly shut down everything.
However, if you want to more polite than these rather brutal methods ( which you may want to do in particular if you have placed some special shut down code in wxApp::OnExit
) then you want to find the top level window and close that. To do this from anywhere in your code
wxGetApp().GetTopWindow()->Close()

Thanks for all the help, I have solved the problem. Seems fairly obvious now but couldn't figure it out at the time!
Originally, my computer vision app was called from a main function. However, with the new GUI code there is no need for a main so I replaced the original main with a shell class.
Though I had been careful to free allocated memory within the methods of my computer vision classes I had not been so careful with the original main function because once that function ended, all memory previously in use would be cleared up by the program's regular exiting.
The difference with the new GUI code is that when the shell class is finished - the program is still running. The clue was in the fact that even when the computer vision app had ended, the blue light on my webcam was still shining.
* Be sure to call cvReleaseCapture( &capture ); to free up that thread and release the hardware *

Your call to Close only closes the frame, but doesn't stop the application, because it is not the last top level window. The wxWidget contains a topic Window Deletion Overview. It states that
A wxWidgets application automatically exits when the last top level window (wxFrame or wxDialog), is destroyed. Put any application-wide cleanup code in wxApp::OnExit (this is a virtual function, not an event handler).
Is your frame the top-level frame? If not, you may have to call Close or Destroy on a top-level frame.

Related

QT5.3.2 + VTK6.1 C++ program quits randomly after long time running

I have a C++ program written together with QT5.3.2 + VTK 6.1. The program compiles fine and can run after deployment. Each function button also works fine.
The problem happens when I run this program for weeks (its a motion control software, so it needs to be on for a long time). Randomly(probably not random at all...) it quits/crashes without a frozen window. In another word, the program window just closes and no error message window appears.
I met the memory leak issue before, the program window first froze and the cursor kept busy status and unresponsive. But this time it just closes itself without any error message or unresponsiveness.. Could this also be a memory leak issue?
So I really appreciate it if someone can give me some hint or direction to troubleshoot this issue by their rich experience in programming.
Since there is a lot of code and I do not know where the problem comes from. I will not post code for now but I am happy to include some key aspects:
It uses ADS communication to communicate with hardware drives.
Callback function to fetch the monitoring data and display in QT interface, meaning a lot of actions like LineEdit->SetText() are used repeatedly. SetText() is called with a global qapplication pointer *tp->SetText().
VTK just displays the 3D data. And I separately tested there is no memory leak.
I am happy to share more information if needed.
Memory leak test.

Continuously (asynchronously) poll and update label in C++ GUI application

I have an application that opens another process and modifies its memory. What I'd like to have as a part of the GUI is a label that updates (perhaps every second or so) to let the user know if they're attached to the other process.
When the application is found running, I'm creating a handle to it, obtaining the base address of it, and then the rest of the work is done through button clicks and hotkeys. Anyway, for each time the application is found running, I want it to do all the things I have it do to obtain the handle, etc., etc.
This way, the other application can be closed and reopened without my app also needing to be closed/reopened accordingly.
Thus far, my research has led me to CreateThread() and std::async (as well as std::launch::async and std::launch::deferred). The issue I'm having is I can't seem to find examples of infinitely-running asynchronous code (in its own thread, perhaps). I'm having a difficult time wrapping my head around how to make this happen, as everything I've tried still keeps execution from continuing as if I'd just written a while loop in main() or something.
Anything exemplifying the type of functionality I'm looking to achieve would be immensely appreciated! Thanks for your time and help, everyone.

CEF crashes when calling functions in a particular DLL

I have an MSVC project, this project consists of multiple DLLs called from an executable. One of these DLLs initializes CEF (Chromium Embedded Framework) and another provides some other general functionality, We'll call them cefDLL and generalDLL. The calls go like this:
All the calls are done from the executable.
I call functions in the cefDLL to initialize CEF.
I call functions the second generalDLL.
Some thread internally in CEF crashes with a Windows error popup reporting "The application was unable to start correct (0xc0000124). Click OK to close the application.".
A Windows popup appears declaring Application.exe has stopped working.
The main thread continues running even if I close the program on the "has stopped working" popup.
If I try to run the debugger on the crashed program I get a blank Visual Studio, no call stack, no locals, nothing, not even the name of a failed DLL.
If I call a function from another DLL, a function from the executable itself or none at all, the code reaches my infinite loop just fine (I'm using an infinite loop to stop the rest of the program from running).
If I let it keep running into the rest of the program and don't stop it with an infinite loop two more threads in CEF crash for a total of three crashed threads. These produce exactly the same errors as the first thread. I'm not sure what causes this precisely as I haven't had the time to look into this yet.
Even if the functions called in generalDLL do absolutely nothing this still occurs. I am certain it is the act of calling them that causes this, if my code is
initializeCEF();
while (true)
{
}
it works, if the code is
initializeCEF();
someBlankFunctionInGeneralDLL();
while (true)
{
}
the thread crashes.
The initialization of CEF consists of this:
//Initialize
CefMainArgs mainArgs;
//Launch Threads
CefExecuteProcess(mainArgs, nullptr, nullptr);
//Settings
CefSettings settings;
settings.pack_loading_disabled = true;
settings.windowless_rendering_enabled = true;
settings.multi_threaded_message_loop = false;
settings.no_sandbox = true;
//Sandbox Info
void *sandboxInfo = nullptr;
//Launch System
CefInitialize(mainArgs, settings, nullptr, sandboxInfo);
Does anyone have the faintest idea what this could be caused by? It's easily among the strangest bugs I've ever encountered.
The project is giant at 50,000 lines or so and there aren't really any other relevant parts so I can't really provide any examples I'm afraid. Let me know if there's some code you think it would help to see though.
You know CEF is multi-process, right? Is it possible that your main application that is initializing CEF is not able to start multiple instances correctly, or is not passing the required command-line arguments to your CEF-containing DLL at startup? See this documentation about the structure of CEF applications: https://bitbucket.org/chromiumembedded/cef/wiki/Architecture#markdown-header-cef3
You can try starting CEF with the "--single-process" argument to force it to run single process (though shipping with this is very much not recommended because they don't test Chromium in this configuration - it is just for debugging). If you are not passing command line arguments to CEF that is probably the start of your problems. To do this, you can add a handler for OnBeforeCommandLineProcessing() in you CefApp derived class, as recommended by the creator of CEF here: http://www.magpcss.org/ceforum/viewtopic.php?f=6&t=12928&p=25732&hilit=main_args#p25717 . The override would end up looking something like this:
void ServiceCenterApp::OnBeforeCommandLineProcessing(const CefString& process_type,
CefRefPtr<CefCommandLine> command_line) {
if(!command_line->HasSwitch("single-process")) {
command_line->AppendSwitch("single-process");
}
}
But I don't see you defining a CefApp derived class, that would be an argument to CefInitialize(). For example, the cefclient sample has this in their wWinMain():
// SimpleApp implements application-level callbacks. It will create the first
// browser instance in OnContextInitialized() after CEF has initialized.
CefRefPtr<SimpleApp> app(new SimpleApp);
followed by
// Initialize CEF.
CefInitialize(main_args, settings, app.get(), sandbox_info);
Where you tell CEF to use the derived App, where you would override whatever handlers you need to. You might want to start with the simple_app sample for a very basic override.
For the debugging issue, try attaching to all processes launched, assuming I'm incorrect and the multiple processes are launching correctly.

Forcing the Qt GUI to update

I am coding a boardgame in Qt where, after the player makes a move, the computer AI must pause and think for some time. However, while it is thinking, it seems the screen will not be updated until every line of code has been executed. Thus, the user would click on a square, see nothing happen for a few seconds, and then suddenly see the result of both his move and the computer's move.
In an attempt to fix this, I tried creating a new thread on which the AI runs its code, and then places its piece on the board. However, sometimes (and this is very inconsistent) the game crashes after the computer has made a move.
So can you guys either:
Tell me how force the MainWindow to update its contents
Help me try to debug the crashing problem (I'm totally new to threads)
EDIT--I tried setting breakpoints as suszterpatt suggested, and the program seems to crash consistently in the debugger (it wasn't before I set the breakpoints).
Anyways, as I step through the program, it seems to go through the run function fine, until it reaches the ending bracket, and then if I step through it jumps into line 317 on qthread_win.cpp, which just says
finish(arg); //line 317
return 0;
If I step through that line, the debugger freezes up and Qt alerts me after 20 seconds. If I continue, I get the "This application has requested the Runtime to terminate it in an unusual way" message that I get when the program occasionally crashes when I'm not debugging.
What should I do now?
The cause of the crash can be a variety of reasons but if I had to take a guess I'd say you're probably calling methods of a GUI object (label, textbox, your game board, etc.) from the AI thread.
The way threads communicate with one another in Qt is through a mechanism called signals and slots: the AI thread should expose a set of signals, i.e. 'beginThink', 'endThink', and the UI thread should register to those signals (with slots) and react accordingly. This is documented pretty throughly in the docs.
Try moving your code out of the separate thread. Once you have it working you can try moving it back and you will know any issues are threading related. I think your updating issue will go away if it's all on the same thread.

Why is my paintBox Canvas being erased when my program is "Not Responding"?

I have written a small program using Borland's C++ builder, and along the way, everything seemed fine. My program has a map window and a table window, and when a user presses a button, a long process is started that reads in all the map and table information and then displays that. Every time i ran it through the debugger, I had no issues. Then today, I decided to test it without running it through the debugger. To my horror, The program reads in the map information and then displays it on the paintbox canvas without a problem, but when it loads the information for the grid, the map gets erased!!! It appears to happen during the load phase for the table. this takes about 4 seconds, and during which time, the window tells me that it isnt responding. This is when the map gets erased. Anyone have any ideas on why this is happening? Its driving me nuts, and I dont really understand whats going on under the hood here.
UPDATE:
I have fixed the problem to some degree. I was poking around and found this: Avoiding "(Not Responding)" label in windows while processing lots of data in one lump
I added the code to run once in the middle of the data read in for the table. this fixed my problems. however, I was wondering if anyone knows why this is the case? why does my program going unresponsive cause my canvases to be erased?
Marcus Junglas wrote a detailed explanation of the problem, which affects both Delphi and C++Builder.
When programming an event handler in
Delphi (like the OnClick event of a
TButton), there comes the time when
your application needs to be busy for
a while, e.g. the code needs to write
a big file or compress some data.
If you do that you'll notice that your
application seems to be locked. Your
form cannot be moved anymore and the
buttons are showing no sign of life.
It seems to be crashed.
The reason is that a Delpi application
is single threaded. The code you are
writing represents just a bunch of
procedures which are called by
Delphi's main thread whenever an event
occured. The rest of the time the main
thread is handling system messages and
other things like form and component
handling functions.
So, if you don't finish your event
handling by doing some lengthy work,
you will prevent the application to
handle those messages.
You can reduce the problem by calling Application->ProcessMessages(), while loading your map data, however I recomend using a separate thread to load the data.
I have never used C++ Builder, but i used Delphi. I think the libraries are the same.
Does that component you use store the image data? It may only draw to the screen. Try covering the window of your app with another window. If it erases it, you have to use a component which stores the image.
See this, it is for Delphi, but it may help. There should be a Image component in C++ Builder. Try using that instead of PaintBox.
You can solve the unresponsivenes problem by running the time consuming task in a separate thread or calling some function that processes the window's messages.