/** * Set up a Un*x signal handler to call {@link #restartApplication(Runnable, boolean)} when the signal * is received. * * @param signalName Name of the signal. * @param onExit A runnable to perform on exit. * @param withNewest If a jar, should we find the newest? * @param pidFile the name of a file to write the process id too */ public static void onSignal(final String signalName, Runnable onExit, boolean withNewest, String pidFile) { Signal sig = new Signal(signalName); Signal.handle(sig, signal -> { restartApplication(onExit, withNewest); }); if (pidFile != null) { final Path pidFilePath = Paths.get(pidFile); try { Files.deleteIfExists(pidFilePath); Files.createFile(pidFilePath); Files.write(pidFilePath, String.format("%d\n", getProcessPid()).getBytes()); } catch (IOException e) { throw new UncheckedIOException("Can not create pid file: " + pidFile, e); } } }
/** * Initializes basic features of the VM, including all of the VM schemes and the trap handling mechanism. * It also parses some program arguments that were not parsed earlier. */ protected final void initializeBasicFeatures() { MaxineVM vm = vm(); vm.phase = MaxineVM.Phase.STARTING; // Now we can decode all the other VM arguments using the full language if (VMOptions.parseStarting()) { VMLog.checkLogOptions(); vmConfig().initializeSchemes(MaxineVM.Phase.STARTING); if (Heap.ExcessiveGCFrequency != 0) { new ExcessiveGCDaemon(Heap.ExcessiveGCFrequency).start(); } if (Deoptimization.DeoptimizeALot != 0 && Deoptimization.UseDeopt) { new DeoptimizeALot(Deoptimization.DeoptimizeALot).start(); } // Install the signal handler for dumping threads when SIGHUP is received Signal.handle(new Signal("QUIT"), new PrintThreads(false)); } }
@Override public void handle(Signal signal) { if (signalCount == 0) { System.out.println("Terminating from signal"); if (server != null) { server.initiateShutdown(); } else { System.out.println("...but no server found? Dazed, confused and doing nothing."); } System.out.println("A second signal will trigger standard Forge shutdown, a third will trigger abrupt termination."); } else if (signalCount == 1) { System.out.println("Caught second signal, triggering Forge-standard shutdown."); FMLCommonHandler.instance().exitJava(1, false); } else { System.out.println("Caught third signal, triggering abrupt termination. Corruption is possible."); FMLCommonHandler.instance().exitJava(2, true); } signalCount++; }
@Test(dataProvider = "supportedSignals") static void testEquals(String name, IsSupported supported, CanRegister register, CanRaise raise, Invoked invoked) { Object[][] data = supportedSignals(); for (int i = 0; i < data.length; i++) { IsSupported otherSupported = (IsSupported) data[i][1]; if (supported == IsSupported.NO || otherSupported == IsSupported.NO) { continue; } String otherName = (String) data[i][0]; Signal sig1 = new Signal(name); Signal sig2 = new Signal(otherName); if (name.equals(otherName)) { Assert.assertEquals(sig1, sig2, "Equals failed; "); Assert.assertEquals(sig1.hashCode(), sig2.hashCode(), "HashCode wrong; "); } else { Assert.assertNotEquals(sig1, sig2, "NotEquals failed; "); Assert.assertNotEquals(sig1.hashCode(), sig2.hashCode(), "HashCode wrong; "); } } }
@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); } } }
/** * Provided as part of the signal handling interface. Calls rotate(). */ @Override public void handle ( Signal arg0 ) { final String signame = arg0.getName (); if ( signame.equals ( fSignal ) ) { log.info ( "Received signal " + arg0 + "; rotating." ); rotate (); log.info ( "Log rotation complete." ); } else { log.info ( "Received signal " + arg0 + "; ignored." ); } }
@Override public void handle(Signal signal) { try { for (Server server : servers) { if (server != null) { server.stop(); logger.info(server.getClass().getSimpleName() + " is stopped..."); while (server.running()) { try { Thread.sleep(100L); } catch (InterruptedException e) { // ignore } } } } } finally { countDownLatch.countDown(); if (signalHandler != SIG_DFL && signalHandler != SIG_IGN) { signalHandler.handle(signal); } } }
public InteractiveShellRunner(@Nonnull StatementExecuter executer, @Nonnull TransactionHandler txHandler, @Nonnull Logger logger, @Nonnull StatementParser statementParser, @Nonnull InputStream inputStream, @Nonnull File historyFile, @Nonnull UserMessagesHandler userMessagesHandler) throws IOException { this.userMessagesHandler = userMessagesHandler; this.currentyExecuting = new AtomicBoolean(false); this.executer = executer; this.txHandler = txHandler; this.logger = logger; this.statementParser = statementParser; this.reader = setupConsoleReader(logger, inputStream); this.historian = FileHistorian.setupHistory(reader, logger, historyFile); // Catch ctrl-c Signal.handle(new Signal(INTERRUPT_SIGNAL), this); }
/** * Catch Ctrl-C from user and handle it nicely * * @param signal to handle */ @Override public void handle(final Signal signal) { // Stop any running cypher statements if (currentyExecuting.get()) { executer.reset(); } else { // Print a literal newline here to get around us being in the middle of the prompt logger.printError( AnsiFormattedText.s().colorRed() .append("\nInterrupted (Note that Cypher queries must end with a ") .bold().append("semicolon. ").boldOff() .append("Type ") .bold().append(Exit.COMMAND_NAME).append(" ").boldOff() .append("to exit the shell.)") .formattedString()); // Clear any text which has been inputted resetPrompt(); } }
@Test public void testSignalHandleOutsideExecution() throws Exception { // given InputStream inputStream = new ByteArrayInputStream("".getBytes()); InteractiveShellRunner runner = new InteractiveShellRunner(cmdExecuter, txHandler, logger, new ShellStatementParser(), inputStream, historyFile, userMessagesHandler); // when runner.handle(new Signal(InteractiveShellRunner.INTERRUPT_SIGNAL)); // then verifyNoMoreInteractions(cmdExecuter); verify(logger).printError("@|RED \nInterrupted (Note that Cypher queries must end with a |@" + "@|RED,BOLD semicolon. |@" + "@|RED Type |@@|RED,BOLD :exit|@@|RED,BOLD |@" + "@|RED to exit the shell.)|@"); }
@Test public void testSignalHandleDuringExecution() throws Exception { // given BoltStateHandler boltStateHandler = mock(BoltStateHandler.class); FakeInterruptableShell fakeShell = spy(new FakeInterruptableShell(logger, boltStateHandler)); InputStream inputStream = new ByteArrayInputStream("RETURN 1;\n".getBytes()); InteractiveShellRunner runner = new InteractiveShellRunner(fakeShell, fakeShell, logger, new ShellStatementParser(), inputStream, historyFile, userMessagesHandler); // during Thread t = new Thread(runner::runUntilEnd); t.start(); // wait until execution has begun while (!t.getState().equals(Thread.State.TIMED_WAITING)) { Thread.sleep(100L); } // when runner.handle(new Signal(InteractiveShellRunner.INTERRUPT_SIGNAL)); // then verify(fakeShell).execute("RETURN 1;"); verify(fakeShell).reset(); verify(boltStateHandler).reset(); }
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() } }
@Override public void afterPropertiesSet() throws Exception { if(LangUtils.isEmpty(graceKillProcessor)){ return ; } AnnotationAwareOrderComparator.sort(graceKillProcessor); graceKillProcessor.stream().forEach(p->{ p.getSignals().forEach(s->{ if(logger.isWarnEnabled()){ logger.warn("register kill signal {}...", s); } Signal.handle(new Signal(s), this); }); }); }
@Override public void handle(Signal signal) { if(logger.isWarnEnabled()){ logger.warn("receive kill signal {}...", signal.getName()); } if(LangUtils.isEmpty(graceKillProcessor)){ return ; } final SignalInfo info = SignalInfo.builder() .name(signal.getName()) .number(signal.getNumber()) .build(); graceKillProcessor.stream() .filter(p->p.getSignals().contains(info.getName())) .forEach(p->{ logger.warn("start to execute GraceKillProcessor[{}] ...", p.getClass()); try { p.handle(info); } catch (Exception e) { logger.error("execute GraceKillProcessor["+p.getClass()+"] error: ", e); } logger.warn("has executed GraceKillProcessor[{}] ...", p.getClass()); }); }
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; }
@Override public void handle(Signal signal) { logger.info("Shutting down carbon server"); readerServer.shutdown(); logger.info("Shutting down index service"); indexService.shutdown(); logger.info("Shutting down C* service"); cassandraService.shutdown(); logger.info("Shutting down stats service"); statsService.shutdown(); logger.info("Shutdown complete"); System.exit(0); }
@Override public void handle(Signal signal) { logger.info("Received sighup"); logger.info("Reloading throttling configuration"); try { ThrottlingConfiguration throttlingConfiguration; File file = new File(throttlingConfigLocation); if(file.exists() && !file.isDirectory()) { Yaml yaml = new Yaml(); logger.info("Loading throttling configuration"); InputStream in = Files.newInputStream(Paths.get(throttlingConfigLocation)); throttlingConfiguration = yaml.loadAs(in, ThrottlingConfiguration.class); in.close(); } else { throttlingConfiguration = new ThrottlingConfiguration(); } throttlingService.reload(throttlingConfiguration); logger.debug("Running with the following throttling configuration: " + throttlingConfiguration.toString()); } catch (Exception e) { logger.error("Reloading throttling configuration failed"); logger.error(e); } }
@Override public void handle(Signal signal) { if (lastReceived == -1) { return; } final long time = System.currentTimeMillis(); if (time - lastReceived <= 5000) { logger.info("Shutting down the server now!"); tm.runTask(ControlC.class, () -> { Sponge.getServer().shutdown(Text.of()); // tODO default message? lastReceived = -1; }); } else { lastReceived = time; logger.info("You can't copy content from the console using CTRL-C!"); logger.info("If you really want shutdown the server use the stop command or press CTRL-C again within 5 seconds!"); } }
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(); } }); }
@Override public void run() { LOG.info("Start"); while (isRunning) { Signal signal; try { signal = waitingSignals.take(); if (signal != null) { handle(signal); } } catch (Throwable e) { LOG.error("Failed to handle " + e.getCause(), e); } } LOG.info("End"); }
SentenceSourceIndexer(Directory dir, Language language, int maxSentences, Analyzer analyzer) { if (analyzer == null) { this.indexer = new Indexer(dir, language); } else { this.indexer = new Indexer(dir, language, analyzer); } this.indexer.setLowercaseOnly(LC_ONLY); this.maxSentences = maxSentences; Signal.handle(new Signal("HUP"), signal -> { stopped = true; System.out.println("----- Got SIGHUP, will commit and exit ----"); try { indexer.commit(); System.out.println("----- commit done, will exit now ----"); } catch (Exception e) { e.printStackTrace(); } System.exit(1); }); }
@Override public void handle(Signal signal) { System.out.println(signal); // mark that we should quit and interrupt the selector. unregister SIGINT setExitOnSigInt(false); exitLoop(); }
/** * Handle an incoming signal. * * @param signal The incoming signal */ @Override public void handle(Signal signal) { LOG.error("RECEIVED SIGNAL " + signal.getNumber() + ": SIG" + signal.getName()); prevHandler.handle(signal); }
public AbstractSignalHandler() { // kill命令 Signal termSignal = new Signal("TERM"); Signal.handle(termSignal, this); // ctrl+c命令 Signal intSignal = new Signal("INT"); Signal.handle(intSignal, this); }
@Override public void handle(Signal signal) { System.out.println("Signal handler called for signal " + signal); try { System.out.println("politely exiting, please wait 3 seconds..."); running = false; } catch (Exception e) { System.out.println("handle|Signal handler" + "failed, reason " + e.getMessage()); e.printStackTrace(); } }
public static void main(String[] args) { StatMessageSender sender = new StatMessageSender(); // kill命令 Signal termSignal = new Signal("TERM"); Signal.handle(termSignal, sender); // ctrl+c命令 Signal intSignal = new Signal("INT"); Signal.handle(intSignal, sender); sender.run(); }
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); } }
@Override public void handle(Signal signal) { try { logger.info("stopping manager..."); manager.stop(); manageExector.shutdownNow(); client.close(); dfsManager.close(); } catch (Throwable e) { logger.error("handle|Signal handler" + "failed, reason " + e.getMessage()); } }
@Override public void handle(Signal signal) { try { logger.info("stopping server..."); server.stop(); logger.info("stopping zk client..."); client.close(); logger.info("stopping other service..."); dfsManager.close(); serviceThreadPool.shutdown(); } catch (Throwable e) { logger.error("handle|Signal handler" + "failed, reason " + e.getMessage()); } }