gpt4 book ai didi

android - C++ 信号处理程序无法通知 Java 端

转载 作者:行者123 更新时间:2023-11-30 03:21:44 28 4
gpt4 key购买 nike

我有以下 CPP 代码。我想做的是,当我的 native 端发生错误时,我会通知 Java 该错误。我用了How can I catch SIGSEGV (segmentation fault) and get a stack trace under JNI on Android?作为引用。

static JavaVM* g_JVM = NULL;
static jobject g_thejavaobject = NULL;

void InitializeNativeSide(JNIEnv *env, jclass, jobject object)
{
env->GetJavaVM(&g_JVM);
g_thejavaobject = env->NewGlobalRef(object);
}

// this executes in another thread running in parallel with UI thread
void StartExecuting(JNIEnv *_env, jclass) {
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_sigaction = SignalErrorHandler;
sa.sa_flags = SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);

// native starts executing here. after a while, a SEGFAULT is encountered
// triggering SignalErrorHandler()
...
}

void SignalErrorHandler(int signal, siginfo_t *si, void *arg)
{
JNIEnv *env;
g_JVM->GetEnv((void**)&env, JNI_VERSION_1_6);

jclass myClass = env->FindClass("com/company/MyClass");
jmethodID myMethod = env->GetMethodID(myClass, "nativeCrashed", "()V" );
env->CallVoidMethod(g_thejavaobject, myMethod);

env->DeleteLocalRef(myClass);
}

一切正常,但对 myClass.nativeCrashed() 的调用不起作用。我做错了什么?

最佳答案

你不能这样做:

void SignalErrorHandler(int signal, siginfo_t *si, void *arg)
{
JNIEnv *env;
g_JVM->GetEnv((void**)&env, JNI_VERSION_1_6);

jclass myClass = env->FindClass("com/company/MyClass");
jmethodID myMethod = env->GetMethodID(myClass, "nativeCrashed", "()V" );
env->CallVoidMethod(g_thejavaobject, myMethod);

env->DeleteLocalRef(myClass);
}

至少出于两个根本原因,这行不通。

首先,只能从信号处理程序中调用异步信号安全函数。可以在 http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04_03 找到 POSIX 指定的列表。 .

没有 Java JNI 调用是异步信号安全的。

第二,the Java JVM uses SIGSEGV internally - 得到一个 SIGSEGV 不一定是致命的:

Signals Used in Oracle Solaris, Linux, and macOS

...

SIGSEGV, SIGBUS, SIGFPE, SIGPIPE, SIGILL These signals are used in the implementation for implicit null check, and so forth.

关于android - C++ 信号处理程序无法通知 Java 端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841696/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com