Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add signal handling for SIGTERM in addition to SIGINT #1259

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion native/common/jp_context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -489,10 +489,14 @@ 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;
#if PY_MINOR_VERSION<10
PyErr_SetInterrupt();
#else
PyErr_SetInterruptEx((int) signal);
#endif
}

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();
}
76 changes: 76 additions & 0 deletions test/jpypetest/test_signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# *****************************************************************************
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# See NOTICE file for details.
#
# *****************************************************************************
import os
import signal
import sys
import threading
import unittest
import jpype
import subrun


@subrun.TestCase
class SignalsTest(unittest.TestCase):

@classmethod
def setUpClass(cls):
# set up signal handling before starting jpype
cls.sigint_event = threading.Event()
cls.sigterm_event = threading.Event()

def sigint_handler(sig, frame):
cls.sigint_event.set()

def sigterm_handler(sig, frame):
cls.sigterm_event.set()

signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGTERM, sigterm_handler)

# start jpype with interrupt=False to pass back control to python
jpype.startJVM(interrupt=False)

def setUp(self):
if sys.platform == "win32":
raise unittest.SkipTest("signals test not applicable on windows")
self.sigint_event.clear()
self.sigterm_event.clear()

def testSigInt(self):
os.kill(os.getpid(), signal.SIGINT)

# the test is executed in the main thread. The signal cannot interrupt the threading.Event.wait() call
# so asserting the return value of `wait` does not work.
# However, after returning from the wait, the control should go to the signal handler, and the next `is_set`
# call will reflect the actual value of the flag.
self.sigint_event.wait(0.1)
self.assertTrue(self.sigint_event.is_set())
self.assertFalse(self.sigterm_event.is_set())

def testSigTerm(self):
os.kill(os.getpid(), signal.SIGTERM)

self.sigterm_event.wait(0.1)
if sys.version_info < (3, 10):
# python versions below 3.10 do not support PyErr_SetInterruptEx
# so SIGTERM will be sent as SIGINT to the interpreter
self.assertTrue(self.sigint_event.is_set())
self.assertFalse(self.sigterm_event.is_set())
else:
self.assertTrue(self.sigterm_event.is_set())
self.assertFalse(self.sigint_event.is_set())