Issue
I'm writing an Android NDK app which consists of a large platform-independent core in C with a few lines of Java glue code based on the android.app.NativeActivity
class. This is working really fine except one thing which is giving me headaches.
The problem is that Android apps do not really quit when calling ANativeActivity_finish()
but instead they are just put into some sort of idle state and AFAIU they are only really killed when Android needs the resources.
This Android peculiarity is a huge problem for me because my C core uses lots of global variables and they aren't reset to 0 when my C core runs its shutdown code. Thus, when Android launches my app after it has been shutdown, all globals contain some random state from the last time my app was run instead of 0.
This isn't a problem at all on all the desktop systems supported by my program (Win32, Mac OS, Linux) because on those systems programs can really quit. But on Android this is fundamentally different. Yes, I know that global variables are bad and that I should reset them to 0 when finished with them but we're talking about a very large C core that has been in development for almost 20 years now so it would require a massive effort to clean this all up just for Android.
That's why I'd like to ask whether there is some way to force Android to always zero out all my globals just like when the app is started for the very first time.
I've already done some research and AFAICS the only way to do this would be to really kill my application using android.os.Process.killProcess()
but this looks like a brute-force method. Isn't there any other way to always get zeroed globals when starting my app?
Solution
The initial zeroing is performed by the operating system -- the variable storage occupies newly-mapped pages. There is no "zero out the stuff that needs zeroing" internal function to call.
You have two basic approaches:
- Make the Android app work like it does on other platforms, and kill the app manually to force a reload.
- Make your app work like Android, and don't act like it's shutting down completely when it gets paused. In other words, don't ever run your shutdown code. You still need to release significant resources when the app gets paused, but that should be less of a burden than tearing everything down.
How feasible approach #2 is depends on the nature of your code.
Yes, I know that global variables are bad and that I should reset them to 0 when finished with them but
If you absolutely must use globals, create a single global structure and pile everything into it, so if you need to reset it or dump all the state in a debugger, it's easy to find everything. It's not ideal, but it's far easier to manage than hunting for scattered globals and (heaven forfend) static locals.
Answered By - fadden
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.