GLFW how to ensure glfwTerminate is called when the program exits? - c++

In GLFW documentation it is written that glfwTerminate will
This will destroy any remaining window, monitor and cursor objects, restore any modified gamma ramps, re-enable the screensaver if it had been disabled and free any other resources allocated by GLFW.
and that one should call it before terminating the program. From my understanding that means, that if this function is not called the operating system doesn't have to re-enable the screensaver or restore modified gamma ramps, which is bad. How do I ensure that it is called regardless of how the program ends?
It's possible to use std::atexit to ensure it is called at the end if the program is exited via the exit command or by returning from the main function. It is also possible to do that making an object with a destructor in the main function that terminates when it is destroyed. The problem is what to do when the program ends with a signal. It's not possible to just register a function using std::signal, because glfwTerminate calls standard library functions other than the ones listed in https://en.cppreference.com/w/cpp/utility/program/signal which the site says is undefined behavior.
How do I ensure the program calls glfwTerminate? Or is it just not possible? And do I understand it correctly that without it the program can leave a modified gamma ramp after getting a signal? And are there any other ways the program can stop without calling the function?

There is no guarantee that the program will call glfwTerminate in case of segfaults or other undefined errors, so it is better to handle all errors before you decide to close it. So, recommendation is calling before the program terminates to restore the modified gamma ramps and re-enable the screensave.

Related

How to properly use _beginthread and endthread

I'm used to work with good old WinAPI call CreateThread(), and check thread's status using the waiting function, e.g WaitForSingleObject(), Once thread thread is signaled with WAIT_OBJECT_0, i close it using CloseHandle().
Recently I've decided to move to beginthread and somehow avoid the risks of uninitialized crt and accidental memory leaks that may happen.
Doing that got me confused.
What's the exact purpose of endthread()? why when i call CloseHandle() in the main function, after thread's execution, CloseHandle() crashes with invalid handle?
Should i ever close the handle returned by beginthread?
endthread, As i understood is invoked automatically by the thread once my function goes out of scope, so should i call it anyway just before i get out of scope?
According to msdn, endthread already calls CloseHandle() 1.From where does the thread obtain a reference / instance to its handle. 2. If i do insist on using endthread(), should it be the last command in the thread?
thanks
EDIT: MSDN paper describing the leaks, here.
As stated in the comments by David Hefferman you can simply change your code back to using CreateThread. The Visual C++ runtime (CRT) will automatically initialize the CRT's per thread data the first time you use a function that uses the per thread data.
The CRT will also automatically free the per thread data when a thread ends, so using CreateThread won't cause memory leaks. There is one exception, if all of the following conditions are true then per thread data isn't automatically freed:
You're building an executable, not a DLL
You're linking against the static version of the CRT library (LIBCMT.LIB) instead of the DLL version (MSVCRT.LIB)
The executable you built is run under Windows XP (or an earlier version of Windows).
Note that even if all this true in your case, the memory leak isn't going to be significant unless you're creating a long lived application that creates and destroys hundreds of thousands of threads over its life time.
If you still want to use the CRTs thread creation functions (_beginthread/_beginthreadex) you should follow these guidelines:
Never use the handle returned by _beginthread. With _beginthread the thread handle is automatically closed when the thread exits, which can potentially happen before _beginthread even returns. You can't use it with WaitForSingleObject safely because the thread might have already exited before you call this function. If you want to use the thread handle for anything use _beginthreadex instead.
You should never close the handle returned by _beginthread. The CRT will do it automatically, and as described in the previous point, may do so before you have chance to.
You should always close the handle returned by _beginthreadex when you no longer need it. The CRT won't do this automatically for you, so it's your own responsibility.
Don't call _endthread or _endthreadex unless you want to quickly and abnormally terminate the thread. While the CRT will free its own per thread data, none of the C++ destructors for any of the thread's objects will be called. It behaves similarly to how _exit ends the process without calling destructors.
The normal means of ending a thread should be by returning from the function passed as an argument to _beginthread or _beginthreadex. This will result in C++ destructors being called as a normal part of the function return.

Calling shared libraries without releasing the memory

In Ubuntu 14.04, I have a C++ API as a shared library which I am opening using dlopen, and then creating pointers to functions using dlsym. One of these functions CloseAPI releases the API from memory. Here is the syntax:
void* APIhandle = dlopen("Kinova.API.USBCommandLayerUbuntu.so", RTLD_NOW|RTLD_GLOBAL);
int (*CloseAPI) = (int (*)()) dlsym(APIhandle,"CloseAPI");
If I ensure that during my code, the CloseAPI function is always called before the main function returns, then everything seems fine, and I can run the program again the next time. However, if I Ctrl-C and interrupt the program before it has had time to call CloseAPI, then on the next time I run the program, I get a return error whenever I call any of the API functions. I have no documentation saying what this error is, but my intuition is that there is some sort of lock on the library from the previous run of the program. The only thing that allows me to run the program again, is to restart my machine. Logging in and out does not work.
So, my questions are:
1) If my library is a shared library, why am I getting this error when I would have thought a shared library can be loaded by more than one program simultaneously?
2) How can I resolve this issue if I am going to be expecting Ctrl-C to be happening often, without being able to call CloseAPI?
So, if you do use this api correctly then it requires you to do proper clean up after use (which is not really user friendly).
First of all, if you really need to use Ctrl-C, allow program to end properly on this signal: Is destructor called if SIGINT or SIGSTP issued?
Then use a technique with a stack object containing a resource pointer (to a CloseAPI function in this case). Then make sure this object will call CloseAPI in his destructor (you may want to check if CloseAPI wasn't called before). See more in "Effective C++, Chapter 3: Resource Management".
That it, even if you don't call CloseAPI, pointer container will do it for you.
p.s. you should considering doing it even if you're not going to use Ctrl-C. Imagine exception occurred and your program has to be stopped: then you should be sure you don't leave OS in an undefined state.

Is it well-defined behaviour to exit the program before main?

It's definitely possible to execute code before main is called, as seen by many examples in this question.
However, what if in that pre-main code, the program is told to exit via std::exit or std::abort? Since main is defined as the start of a program, what consequences are there from exiting before the start?
Upon printing something in each section, I get the following results:
Format:
Section: output
Main: main
Init (called before main): init
Exit (set up with std::atexit inside Init): exiting
Sample runs:
Init called without exiting:
init
main
returns 0
Init calls std::exit(0):
init
returns 0
Init calls std::abort:
init
crashes and returns 3 on Windows with GCC 4.7.2
crashes and brings up the usual box with VS11
returns 0 on LiveWorkSpace
Init sets handler and calls std::exit(0):
init
exiting
returns 0
Init sets handler and calls std::abort:
init
same deal as without the handler
While searching, I saw this question: Is there any way a C/C++ program can crash before main()?. However, it doesn't answer what I want to know: Is any of this behaviour, calling std::exit or std::abort before main, well-defined? Is any of this undefined behaviour?
The short answer is: there are (almost) no consequences. Some destructors may not be called if you unexpectedly call exit, but that's pretty much it.
Generally, not calling destructors is not the cleanest possible way, but then again the end result will be the same.
When a process terminates (via exit or abort or simply by segfaulting, or another reason), handles (kernel objects, files, etc.) are closed, and the memory associated with the program's address space is reclaimed by the operating system.
There is not much else to it either, because when you call exit or abort, you're basically requesting that the program terminates (these functions never return!) so you really can't expect anything to happen thereafter.
Note that registering a function like Init to be called before main is non-standard stuff, but you can get the same effect by having a constructor in a global.

exit() function fails to exit process

I'm working on a multithreaded C++ application in Linux with FreeGLUT. Oddly enough, calling exit() in one of my threads results in an onexit() callback being called and completed, but fails to exit my program. Instead it hangs in a select() call in the GLUT library, according to GDB.
I also have a keyboard callback that exits when I press 'q'. GLUT exits fine if I press 'q' while the program is hanging.
No one seems to be having similar problems. Documentation says that exit() is supposed to close an entire process, and not just a thread, so it's not that. I'm stumped. Do you have any ideas?
EDIT: I've found the problem. I was wrong that the exit handler had finished. A library function call was waiting on a mutex that was already locked at the time that exit() was called. GLUT just took advantage of the free time. Thank you all for your responses.
In C++03
Note: exit() is a C function.
C as a language does not have the concept of threads at the language level.
Threads are usually added to C via a library support. So you need to read the library documentation of the affects of calling exit() from a thread that is not the main thread.
It is probably not portable across threading implementations.
Your best bet is to only call exit() from the main thread.
In a child thread you should probably just set some state that is viewed by the main thread. Let the main thread see this state and call exit manually. Note even calling exit on the man thread may hang some threading libraries if their are child threads still running. So best to get the main thread to wait for all children before exiting if you want your code to be portable.
In C++11
Now that C++11 has entered the since with explicit threading in the language there is more to it. See n3376 Section 18.4.1 [cstdint.syn] Paragraph 8
The function exit() has additional behavior in this International Standard:
— First, objects with thread storage duration and associated with the current thread are destroyed. Next, objects with static storage duration are destroyed and functions registered by calling atexit are called.
See 3.6.3 for the order of destructions and calls. (Automatic objects are not destroyed as a result of calling exit().)
If control leaves a registered function called by exit because the function does not provide a handler for a thrown exception, std::terminate() shall be called (15.5.1).
— Next, all open C streams (as mediated by the function signatures declared in ) with unwritten buffered data are flushed, all open C streams are closed, and all files created by calling tmpfile() are removed.
— Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

Exiting from C++ Console Program

I currently have a program which has the following basic structure
main function
-- displays menu options to user
-- validates user input by passing it to a second function (input_validator)
-- if user selects option 1, run function 1, etc
function1,2,3,etc
-- input is requested from user and then validated by input_validator
-- if input_validator returns true, we know input is good
Here is my problem. I want to allow the user to quit at any point within the program by typing '0'. I planned on doing this with some basic code in input_validator (if input = 0, etc).
This would appear to be simple, but I have been told that using quit() will result in some resources never been released / etc. I cannot simply do a 'break' either -- it will result in my program simply returning to the main function.
Any ideas?
One possibility would be to do it by throwing an exception that you catch in main, and when you catch it, you exit the program. The good point of throwing an exception is that it lets destructors run to clean up objects that have been created, which won't happen if you exit directly from elsewhere (e.g., by using exit()).
exit()
Terminates the process normally,
performing the regular cleanup for
terminating processes.
First, all functions registered by
calls to atexit are executed in the
reverse order of their registration.
Then, all streams are closed and the
temporary files deleted, and finally
the control is returned to the host
environment.
This hasn't been true for any kind of mainstream operating system for a long time. The OS ensures that all kernel resources are released, even if the program didn't explicitly do so. Calling abort() or exit() from anywhere in your code is fine.
exit(int exitCode) - defined in stdlib.h / cstdlib - you'd probably want to exit(0); // normal termintation.
exit() will not call your destructors, so you might want to consider using an exception handler instead.
If you have things like open but unflushed files, the OS will close the file handles, but won't flush any unwritten data.
You have to design your menu system so that a status can be passed back to the previous method, unwinding until code in the main function is executed. Similar issues apply to back or previous screen buttons.
Taking a step back and looking at the Big Picture, the unwinding technique looks very similar to C++ exception handling strategy. I suggest using exceptions for cases that don't follow the normal flow of execution, such as main menu, and previous menu.
Try it out.