java code :
$ cat SignalExample.java public class SignalExample { static { System.loadLibrary("SignalLibrary"); // Load the native library } // Native method declaration public native void waitForSignal(); public static void main(String[] args) { System.out.println("Start.."); SignalExample signalExample = new SignalExample(); signalExample.waitForSignal(); System.out.println("End"); } }jni code:
$ cat SignalLibrary.c #include <jni.h> #include <stdio.h> #include <signal.h> // Global variable to indicate whether the signal has been received volatile sig_atomic_t signalReceived = 0; // Signal handler function void handleSignal(int signo) { signalReceived = 1; } // Native method implementation JNIEXPORT void JNICALL Java_SignalExample_waitForSignal(JNIEnv *env, jobject obj) { // Set up signal handler signal(SIGUSR1, handleSignal); // Wait for the signal while (!signalReceived) { // Perform other work or sleep if needed // ... } printf("Signal received!\n"); }
build code..
先build jni..
先 export 我的 jdk 位置
$ export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64compile jni C:
$ gcc -shared -o libSignalLibrary.so -fPIC -I$JAVA_HOME/include -I$JAVA_HOME/include/linux SignalLibrary.c然後 compile java
javac SignalExample.java
TEST run:
run 的時候要告訴他 so 在哪裡...
$ java -Djava.library.path=/home/charles-chang/ SignalExample Start.. Signal received! End在Start.. 的時候就停了,開啟另一個 terminal 找這個process 的 PID,下signal:
charles+ 3994772 98.5 0.1 11275340 36368 pts/2 Sl+ 10:14 0:03 java -Djava.library.path=/home/charles-chang/ SignalExample ... $ kill -SIGUSR1 3994772就會出現 "Signal received, End",然後結束。
如果不送SIGUSER1,改用 Ctrl-C,就會...
$ java -Djava.library.path=/home/charles-chang/ SignalExample Start.. ^C不會有 Signal received 和 End,會直接結束。
- 這個 example 是 chatgpt 寫的
沒有留言:
張貼留言