Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send events/signal from C to Java in JNI

Is there any mechanism to send asynchronous events/signals through JNI from C to Java or viceversa? I need to catch a signal/event from C to Java.

like image 507
Anil Arrabole Avatar asked Feb 18 '11 19:02

Anil Arrabole


People also ask

Where is JNI?

The JNI header " jni. h " provided by JDK is available under the " <JAVA_HOME>\include " and " <JAVA_HOME>\include\win32 " (for Windows) or " <JAVA_HOME>\include\linux " (for Ubuntu) [Check Mac OS X] directories, where <JAVA_HOME> is your JDK installed directory (e.g., " c:\program files\java\jdk10.

What is Java native code?

The JNI is a native programming interface. It allows Java code that runs inside a Java Virtual Machine (VM) to interoperate with applications and libraries written in other programming languages, such as C, C++, and assembly.

How does JNI work in Java?

It defines a way for the bytecode that Android compiles from managed code (written in the Java or Kotlin programming languages) to interact with native code (written in C/C++). JNI is vendor-neutral, has support for loading code from dynamic shared libraries, and while cumbersome at times is reasonably efficient.

How do you call JNI in C++?

Excample 3: Java Static Method Taking Arguments And Returning Values. JNI passes and returns object of a basic Java type such as int , long , double by value. This is very easy to process. You just have to use the corresponding JNI native type jint , jlong , jdouble and so on.


1 Answers

It sounds a bit tricky, as JNI is supposed to be one-way only: Java code can invoke a native method, which of course may call back into Java code, but can't itself initiate the process.

But it isn't impossible, I think the most straightforward solution is to have a native call that blocks until the signal is received.

Another option would be to write a JVMTI agent, which can interfere with a running VM actively.

But if we're talking about UNIX signals, you can handle then with the not public API (therefore not guaranteed in the future and Sun VM specific) but existing sun.misc.Signal class.

like image 81
biziclop Avatar answered Sep 28 '22 17:09

biziclop