Invoking Java from C++: how to catch/detect a fatal JVM error?

坚强是说给别人听的谎言 提交于 2019-12-23 12:47:01

问题


I'm developing a C++ program (Win32, MS Visual Studio 2008) which creates a Java VM via JNI as outlined here. It has been working fine for a long time, with both Java 6 and Java 7.

Today I have installed a new version of JRE; something went wrong in the installer, and the JRE become corrupt. I noticed that my C++ program doesn't start and doesn't issue any warning messages. Debugging the program showed that it runs successfully until the JNI_CreateJavaVM call; but calling JNI_CreateJavaVM causes the program to instantly terminate. No return values, no error messages, nothing.

Yes, I know that I simply have to reinstall JRE. But nevertheless I'd like my C++ program to be prepared to such situation. If it's unable to create a Java VM, it should show a message "Please reinstall JRE". But I don't have a chance to show that message because the whole program is terminating.

Is there a way to detect such type of errors in JRE, or more generally, in a third-party library? I tried using C++ try/catch constructs, I tried using the signal function - nothing helps; the program disappears without calling any catch or signal handlers.

Is there a way to detect such JRE crash? Or: is there a way to reliably detect a crash or termination inside a third-party library?


回答1:


If you are using Linux/Unix: this is what I usually start with:

struct sigaction sa;
sa.sa_handler = bt_sighandler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;

sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGUSR1, &sa, NULL);

If you are using Microsoft C++ on windows: _try/_except will usually do the trick. It is a MSVC extension (you can tell from the double underscore), which extends standard try/catch.

Try/catch catches C++ exceptions, _try/_except will catch all the other unhandled exceptions (COM, Win32, ...). For example, it will catch null-dereferencing, memory access problems, which are likely the cause of your crash. Read here

Otherwise, in widows, try SetUnhandledExceptionFilter

EDIT: since the approach using SEH seems to fail, you may go one level up and use Vectored Exception Handling. According to this blog post on msdn, VEH is registered per-process, and it is checked before SEH.

If all fails, do not despair :) you can still turn your application into a pair debugger/debugee. That will give you total control over events, life and death of the debugee process. It is generally NOT worth the trouble, but it is an additional solution I had to use in the past. It is also not as difficult as it may seem; if anything else fails, let me know and I'll dig out some old code.



来源:https://stackoverflow.com/questions/14958875/invoking-java-from-c-how-to-catch-detect-a-fatal-jvm-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!