Skip to content

Commit

Permalink
Add signal handling for SIGTERM in addition to SIGINT
Browse files Browse the repository at this point in the history
  • Loading branch information
dfangl committed Jan 30, 2025
1 parent fa54bca commit d7ec22a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 19 deletions.
4 changes: 2 additions & 2 deletions native/common/jp_context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -489,10 +489,10 @@ extern "C" JNIEXPORT void JNICALL Java_org_jpype_JPypeContext_onShutdown

static int interruptState = 0;
extern "C" JNIEXPORT void JNICALL Java_org_jpype_JPypeSignal_interruptPy
(JNIEnv *env, jclass cls)
(JNIEnv *env, jclass cls, jint signal)
{
interruptState = 1;
PyErr_SetInterrupt();
PyErr_SetInterruptEx((int) signal);
}

extern "C" JNIEXPORT void JNICALL Java_org_jpype_JPypeSignal_acknowledgePy
Expand Down
33 changes: 16 additions & 17 deletions native/java/org/jpype/JPypeSignal.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
**************************************************************************** */
package org.jpype;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
Expand All @@ -31,6 +30,17 @@ public class JPypeSignal

static Thread main;

static Object getSignalHandler(Class signalHandlerClazz, int signal) throws ClassNotFoundException {
return Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]
{
signalHandlerClazz
}, (proxy, method, args) -> {
main.interrupt();
interruptPy(signal);
return null;
});
}

static void installHandlers()
{
try
Expand All @@ -39,28 +49,17 @@ static void installHandlers()
Class SignalHandler = Class.forName("sun.misc.SignalHandler");
main = Thread.currentThread();
Method method = Signal.getMethod("handle", Signal, SignalHandler);

Object handler = Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), new Class[]
{
SignalHandler
}, new InvocationHandler()
{
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
main.interrupt();
interruptPy();
return null;
}
});
Object intr = Signal.getDeclaredConstructor(String.class).newInstance("INT");
method.invoke(null, intr, handler);
method.invoke(null, intr, getSignalHandler(SignalHandler, 2));
Object intrTerm = Signal.getDeclaredConstructor(String.class).newInstance("TERM");
method.invoke(null, intrTerm, getSignalHandler(SignalHandler, 15));
} catch (InvocationTargetException | IllegalArgumentException | IllegalAccessException | InstantiationException | ClassNotFoundException | NoSuchMethodException | SecurityException ex)
{
// If we don't get the signal handler run without it. (ANDROID)
}
}

native static void interruptPy();
native static void interruptPy(int signal);

native static void acknowledgePy();
}

0 comments on commit d7ec22a

Please sign in to comment.