public static void enterMainThread() { if(Thread.get_CurrentThread().get_Name() == null) { try { if(false) throw new InvalidOperationException(); Thread.get_CurrentThread().set_Name("main"); } catch(InvalidOperationException _) { } } java.lang.Thread.currentThread(); try{ sun.misc.Signal.handle(new sun.misc.Signal("BREAK"), SignalHandler.SIG_DFL); }catch(IllegalArgumentException ex){ // ignore it; } }
@Test static void testRaiseNoConsumer() { Signal signal = new Signal("INT"); SignalHandler orig = null; try { orig = Signal.handle(signal, SignalHandler.SIG_DFL); printf("oldHandler: %s%n", orig); if (orig == SignalHandler.SIG_IGN) { // SIG_IGN for TERM means it cannot be handled return; } Signal.raise(signal); Assert.fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException iae) { printf("IAE message: %s%n", iae.getMessage()); } finally { // Restore original signal handler if (orig != null && signal != null) { Signal.handle(signal, orig); } } }
@Test() static void checkLastHandler() { if (RUNNING_WITH_Xrs) { return; } Signal signal = new Signal("TERM"); Handler h1 = new Handler(); Handler h2 = new Handler(); SignalHandler orig = Signal.handle(signal, h1); if (orig == SignalHandler.SIG_IGN) { // SIG_IGN for TERM means it cannot be handled return; } try { SignalHandler prev = Signal.handle(signal, h2); Assert.assertSame(prev, h1, "prev handler mismatch"); prev = Signal.handle(signal, h1); Assert.assertSame(prev, h2, "prev handler mismatch"); } finally { if (orig != null && signal != null) { Signal.handle(signal, orig); } } }
/** * Handle the caught signal dumping all locks and threads. */ public void handle(sun.misc.Signal sig) { try { final GemFireStore memStore = GemFireStore.getBootingInstance(); final Signal signal = Signal.valueOfName(sig.getName()); if (Signal.SIGURG.equals(signal)) { final String header = "SIGURG received, full state dump"; GemFireXDUtils.dumpStacks(memStore, header); } else { // just log any other unexpected signals SanityManager.DEBUG_PRINT("warning:SignalHandler", "received explicit OS signal SIG" + sig.getName(), new Throwable()); } // Chain back to previous handler, if one exists SignalHandler oldHandler = this.oldHandlers.get(signal); if (oldHandler != null && oldHandler != SIG_DFL && oldHandler != SIG_IGN) { oldHandler.handle(sig); } } catch (Throwable t) { System.err.println("SigThreadDumpHandler failed to dump to log for SIG" + sig.getName() + ": " + SanityManager.getStackTrace(t)); } }
static void setup() { if (handler != null) return; SignalHandler sh = new SignalHandler() { public void handle(Signal sig) { Shutdown.exit(sig.getNumber() + 0200); } }; handler = sh; try { Signal.handle(new Signal("INT"), sh); Signal.handle(new Signal("TERM"), sh); } catch (IllegalArgumentException e) { // When -Xrs is specified the user is responsible for // ensuring that shutdown hooks are run by calling // System.exit() } }
public void renderOutput(PrintStream out, OutputFormat outputFormat, boolean interactive) { Thread clientThread = Thread.currentThread(); SignalHandler oldHandler = Signal.handle(SIGINT, signal -> { if (ignoreUserInterrupt.get() || client.isClosed()) { return; } userAbortedQuery.set(true); client.close(); clientThread.interrupt(); }); try { renderQueryOutput(out, outputFormat, interactive); } finally { Signal.handle(SIGINT, oldHandler); Thread.interrupted(); // clear interrupt status } }
/** * <p> * startSignalHandler * </p> */ protected void startSignalHandler() { Signal.handle(new Signal("INT"), new SignalHandler() { private boolean interrupted = false; @Override public void handle(Signal arg0) { if (interrupted) System.exit(0); try { interrupted = true; if (process != null) process.waitFor(); } catch (InterruptedException e) { logger.warn("",e); } } }); }
static void setup() { if (handler != null) return; SignalHandler sh = new SignalHandler() { public void handle(Signal sig) { Shutdown.exit(sig.getNumber() + 0200); } }; handler = sh; try { Signal.handle(new Signal("HUP"), sh); Signal.handle(new Signal("INT"), sh); Signal.handle(new Signal("TERM"), sh); } catch (IllegalArgumentException e) { // When -Xrs is specified the user is responsible for // ensuring that shutdown hooks are run by calling // System.exit() } }
public static boolean handleShutdown(Class<?> clazz, String[] args, final AtomicBoolean running) { if (args != null && args.length > 0 && args[0].equals("stop")) { running.set(false); return true; } SignalHandler handler = new SignalHandler() { @Override public void handle(Signal signal) { running.set(false); } }; String command = System.getProperty("sun.java.command"); if (command == null || command.isEmpty()) { return false; } if (clazz.getName().equals(command.split(" ")[0])) { Signal.handle(new Signal("INT"), handler); Signal.handle(new Signal("TERM"), handler); } return false; }
private static void addUnixSignalStatusHandle() { Signal.handle(new Signal("USR2"), new SignalHandler() { @Override public void handle(Signal sig) { System.err.print("::: "+new Date()+" ::: RECIVE SIGNAL "+sig+" ::: Internal Server Status: "); if(sig!=null){ if(status==STATUS_STARTING){ System.err.println("'STATUS_STARTING' :::"); }else if(status==STATUS_RUNNING){ System.err.println("'STATUS_RUNNING' :::"); }else if(status==STATUS_STOPING){ System.err.println("'STATUS_STOPING' :::"); }else{ System.err.println("'STATUS_UNKNOWN' :::"); } } System.err.flush(); } }); }
private void configureSignalHandler() { SignalHandler handler = new SignalHandler() { public void handle(Signal sig) { logger.info("Got " + sig.getName() + " signal, canceling cell execution"); cancelExecution(); } }; if (!isWindows()) { Signal.handle(new Signal("INT"), handler); } }
protected void handleDefault(final sun.misc.Signal sig) { final Signal signal = Signal.valueOfName(sig.getName()); switch (signal) { case SIGINT: break; // ignore the interrupt signal default: final SignalHandler handler = getOriginalSignalHandler(signal); if (handler != null) { handler.handle(sig); } } }
/** * The thread that runs the handler for sun.misc.Signal should be a * Daemon thread. */ @Test static void isDaemonThread() throws InterruptedException { if (RUNNING_WITH_Xrs) { return; } Handler handler = new Handler(); Signal signal = new Signal("INT"); SignalHandler orig = Signal.handle(signal, handler); printf("oldHandler: %s%n", orig); if (orig == SignalHandler.SIG_IGN) { // SIG_IGN for INT means it cannot be handled return; } Signal.raise(signal); boolean handled = handler.semaphore() .tryAcquire(Utils.adjustTimeout(100L), TimeUnit.MILLISECONDS); if (!handled) { // For debug try again printf("Second try to see signal"); handled = handler.semaphore() .tryAcquire(Utils.adjustTimeout(2L), TimeUnit.SECONDS); } Assert.assertEquals(handled, !RUNNING_WITH_Xrs, "raising s.m.Signal did not get a callback;"); Assert.assertTrue(handler.wasDaemon(), "Thread.isDaemon running the handler; "); }
private SigThreadDumpHandler() { this.oldHandlers = Collections .synchronizedMap(new HashMap<Signal, SignalHandler>()); // set of signals to be ignored because they are not fatal or informational List<String> ignoredSignals = new ArrayList<String>() {{ add("WINCH"); add("CHLD"); add("CONT"); add("CLD"); add("BUS"); // Specifically for Mac OS X add("USR1"); add("USR2"); }}; mergeIgnoredSignalsFromProps(ignoredSignals); if (!ignoredSignals.contains("*")) { for (final Signal signal : Signal.values) { if (ignoredSignals.contains(signal.getName())) { continue; } try { sun.misc.Signal osSignal = new sun.misc.Signal(signal.getName()); this.oldHandlers.put(signal, sun.misc.Signal.handle(osSignal, this)); } catch (IllegalArgumentException iae) { // move on to next one } } } }
/** * Handle {@literal INT} signals by calling the specified {@link Runnable}. * @param runnable the runnable to call on SIGINT. */ public static void attachSignalHandler(final Runnable runnable) { Signal.handle(SIG_INT, new SignalHandler() { @Override public void handle(Signal signal) { runnable.run(); } }); }
@Override public void handle() { SignalHandler handler = new SignalHandler() { private int count = 0; @Override public void handle(Signal signal) { if (!signal.getName().equals("INT")) { return; } ++count; if (count == 2) { System.out.println(); System.exit(2); // SIGINT } else { System.out.println("\n(To exit, press ^C again or type :q)"); if (alert != null) { alert.run(); } new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } count = 0; } }).run(); } } }; Signal.handle(new Signal("INT"), handler); }
private static void registerLoggingSignalHandler() { if (!isWindows()) { final Map<String, SignalHandler> jvmSignalHandlers = new ConcurrentHashMap<>(); registerSignalHandler("TERM", jvmSignalHandlers); registerSignalHandler("INT", jvmSignalHandlers); registerSignalHandler("HUP", jvmSignalHandlers); } }
protected static void start(final CloudWatchCollector collector) { Signal.handle(new Signal("HUP"), new SignalHandler() { public void handle(Signal signal) { try { collector.reloadConfig(); } catch (Exception e) { LOGGER.log(Level.WARNING, "Configuration reload failed", e); } } }); }
/** * If running on Windows, do windows-specific setup. */ private static void setupWindows(final Configuration conf, ConfigurationManager cm) { if (!SystemUtils.IS_OS_WINDOWS) { Signal.handle(new Signal("HUP"), new SignalHandler() { @Override public void handle(Signal signal) { conf.reloadConfiguration(); cm.notifyAllObservers(conf); } }); } }
@Override public void start() { if (client != null) { CLIInputObserver cli_input_observer = new CLIInputObserver(client); cli_input_observer.addListener(new CLIInputActionHandler()); Thread cli_input_observer_thread = new Thread(cli_input_observer); cli_input_observer_thread.start(); Signal.handle(new Signal("INT"), new SignalHandler() { @Override public void handle(Signal signal) { sigIntCount++; if (sigIntCount == 4) { // This is only for ugly issues that might occur System.out.println("WARNING: Hitting Ctrl-C again will force close the application."); } else if (sigIntCount == 5) { Signal.raise(new Signal("INT")); Runtime.getRuntime().halt(0); } else if (client.isRunning() && client.isSuspended() == false) { client.askForStop(); System.out.println("Will exit after current frame... Press Ctrl+C again to exit now."); } else { client.stop(); GuiText.this.stop(); } } }); client.run(); client.stop(); } }
@Override public void start() { if (client != null) { CLIInputObserver cli_input_observer = new CLIInputObserver(client); cli_input_observer.addListener(new CLIInputActionHandler()); Thread cli_input_observer_thread = new Thread(cli_input_observer); cli_input_observer_thread.start(); Signal.handle(new Signal("INT"), new SignalHandler() { @Override public void handle(Signal signal) { sigIntCount++; if (sigIntCount == 5) { Signal.raise(new Signal("INT")); Runtime.getRuntime().halt(0); } else if (client.isRunning() && client.isSuspended() == false) { client.askForStop(); exiting = true; } else { client.stop(); GuiTextOneLine.this.stop(); } } }); client.run(); client.stop(); } }
/** * Creates a handler installer that installs signal handlers. */ public static HandlerInstaller createRealHandlerInstaller() { return new HandlerInstaller() { @Override public SignalHandler install(Signal signal, SignalHandler handler) { return Signal.handle(signal, handler); } }; }
@Override public SignalHandler install(Signal signal, SignalHandler handler) { SignalHandler previousHandler = currentHandler; assertWithMessage("This fake only supports the TERM signal") .that(signal) .isEqualTo(TERM_SIGNAL); currentHandler = handler; return previousHandler; }
@Test public void testHandlersCanBeChained() { SignalHandler handler1 = Mockito.mock(SignalHandler.class); SignalHandler handler2 = Mockito.mock(SignalHandler.class); signalHandlers.installHandler(TERM_SIGNAL, handler1); signalHandlers.installHandler(TERM_SIGNAL, handler2); fakeSignalInstaller.sendSignal(); Mockito.verify(handler1).handle(Mockito.eq(TERM_SIGNAL)); Mockito.verify(handler2).handle(Mockito.eq(TERM_SIGNAL)); }
@Test public void testOneHandlerCanHandleSignal() { SignalHandler handler = Mockito.mock(SignalHandler.class); signalHandlers.installHandler(TERM_SIGNAL, handler); fakeSignalInstaller.sendSignal(); Mockito.verify(handler).handle(Mockito.eq(TERM_SIGNAL)); }
/** * Register signal to system * if callback is null, then the current process will ignore this signal */ public synchronized void registerSignal(int signalNumber, Runnable callback, boolean replace) { String signalName = signalMap.get(signalNumber); if (signalName == null) { LOG.warn("Invalid signalNumber " + signalNumber); return; } LOG.info("Begin to register signal of {}", signalName); try { SignalHandler oldHandler = Signal.handle(new Signal(signalName), this); LOG.info("Successfully register {} handler", signalName); Runnable old = signalHandlers.put(signalNumber, callback); if (old != null) { if (!replace) { oldSignalHandlers.put(signalNumber, oldHandler); } else { LOG.info("Successfully old {} handler will be replaced", signalName); } } LOG.info("Successfully register signal of {}", signalName); } catch (Exception e) { LOG.error("Failed to register " + signalName + ":" + signalNumber + ", Signal already used by VM or OS: SIGILL"); } }
/** * Registers the new list of functions to the signal name, and returns the * old SignalHandler. */ private static SignalHandler setHandler(String signame, Seqable fns) { Signal sig = new Signal(signame); SignalFolder folder = new SignalFolder(fns); SignalHandler oldHandler = Signal.handle(sig, folder); return oldHandler; }
/** * Resets/reinits the signal to be handled by its original signal handler. * * @param signame the name of the signal to reinit. */ static synchronized void resetDefaultHandler(String signame) throws SignalHandlerNotFoundException { if (originalHandlers.containsKey(signame)) { SignalHandler original = originalHandlers.get(signame); Signal sig = new Signal(signame); Signal.handle(sig, original); originalHandlers.remove(sig); SignalAtoms.getSignalAtom(signame).reset(getHandlerSeq(signame)); // As the Atom has a watch which calls register, the handle has been // modified again. Perform another handle call to fix this: Signal.handle(sig, original); } }