sun.misc.SignalHandler Java Examples

The following examples show how to use sun.misc.SignalHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SunMiscSignalTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example #2
Source File: SunMiscSignalTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example #3
Source File: SigThreadDumpHandler.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
  }
}
 
Example #4
Source File: SigThreadDumpHandler.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
  }
}
 
Example #5
Source File: TemplateAppContext.java    From hasor with Apache License 2.0 6 votes vote down vote up
public void joinSignal(long timeout, TimeUnit unit) {
    tryShutdown();
    final BasicFuture<Object> future = new BasicFuture<>();
    //
    // .注册 shutdown 事件
    HasorUtils.pushShutdownListener(getEnvironment(), (EventListener<AppContext>) (event, eventData) -> {
        future.completed(new Object());
    });
    //
    // .注册 shutdown 信号
    final SignalHandler signalHandler = signal -> {
        int number = signal.getNumber();
        logger.warn("process kill by " + signal.getName() + "(" + number + ")");
        try {
            future.completed(new Object());
        } catch (Exception e) {
            future.failed(e);
        }
    };
    Signal.handle(new Signal("TERM"), signalHandler);    // kill -15 pid
    Signal.handle(new Signal("INT"), signalHandler);     // 相当于Ctrl+C
    logger.info("register signal to TERM,INT");
    //
    // .阻塞进程
    joinAt(future, timeout, unit);
}
 
Example #6
Source File: JStormSignalHandler.java    From jstorm with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
    }

}
 
Example #7
Source File: ApplicationLifecycleManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void handleSignal(final String signal, final SignalHandler handler) {
    try {
        Signal.handle(new Signal(signal), handler);
    } catch (IllegalArgumentException ignored) {
        // Do nothing
    }
}
 
Example #8
Source File: ReloadSignalHandler.java    From cloudwatch_exporter with Apache License 2.0 5 votes vote down vote up
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);
            }
        }
    });
}
 
Example #9
Source File: SignalHandlersTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #10
Source File: SignalHandlersTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #11
Source File: SignalHandlersTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #12
Source File: SignalHandlers.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
  };
}
 
Example #13
Source File: GuiTextOneLine.java    From sheepit-client with GNU General Public License v2.0 5 votes vote down vote up
@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();
	}
}
 
Example #14
Source File: GuiText.java    From sheepit-client with GNU General Public License v2.0 5 votes vote down vote up
@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();
	}
}
 
Example #15
Source File: ReloadSignalHandler.java    From cloudwatch_exporter with Apache License 2.0 5 votes vote down vote up
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);
            }
        }
    });
}
 
Example #16
Source File: RemoteInterpreterServer.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
    throws TTransportException, InterruptedException, IOException {
  String zeppelinServerHost = null;
  int port = Constants.ZEPPELIN_INTERPRETER_DEFAUlT_PORT;
  String portRange = ":";
  String interpreterGroupId = null;
  if (args.length > 0) {
    zeppelinServerHost = args[0];
    port = Integer.parseInt(args[1]);
    interpreterGroupId = args[2];
    if (args.length > 3) {
      portRange = args[3];
    }
  }
  RemoteInterpreterServer remoteInterpreterServer =
      new RemoteInterpreterServer(zeppelinServerHost, port, interpreterGroupId, portRange);
  remoteInterpreterServer.start();

  // add signal handler
  Signal.handle(new Signal("TERM"), new SignalHandler() {
    @Override
    public void handle(Signal signal) {
      try {
        LOGGER.info("Receive TERM Signal");
        remoteInterpreterServer.shutdown();
      } catch (TException e) {
        LOGGER.error("Error on shutdown RemoteInterpreterServer", e);
      }
    }
  });

  remoteInterpreterServer.join();
  LOGGER.info("RemoteInterpreterServer thread is finished");
  System.exit(0);
}
 
Example #17
Source File: AeronUtil.java    From benchmarks with Apache License 2.0 5 votes vote down vote up
static void installSignalHandler(final AtomicBoolean running)
{
    final SignalHandler terminationHandler = signal -> running.set(false);

    for (final String signalName : ShutdownSignalBarrier.SIGNAL_NAMES)
    {
        Signal.handle(new Signal(signalName), terminationHandler);
    }
}
 
Example #18
Source File: GfshSignalHandler.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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);
      }
  }
}
 
Example #19
Source File: SigThreadDumpHandler.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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
      }
    }
  }
}
 
Example #20
Source File: SimpleStringReader.java    From Latte-lang with MIT License 5 votes vote down vote up
@Override
public void setCtrlCHandler(final CtrlCHandler ctrlCSignalHandler) {
        SignalHandler handler = new SignalHandler() {
                @Override
                public void handle(Signal signal) {
                        if (!signal.getName().equals("INT")) {
                                return;
                        }
                        ctrlCSignalHandler.handle();
                }
        };
        Signal.handle(new Signal("INT"), handler);
}
 
Example #21
Source File: GfshSignalHandler.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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);
      }
  }
}
 
Example #22
Source File: SigThreadDumpHandler.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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
      }
    }
  }
}
 
Example #23
Source File: SunMiscSignalTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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; ");
}
 
Example #24
Source File: GfshSignalHandler.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
protected SignalHandler getOriginalSignalHandler(final Signal signal) {
  final SignalHandler handler = originalSignalHandlers.get(signal);
  return (handler == SignalHandler.SIG_DFL || handler == SignalHandler.SIG_IGN ? null : handler);
}
 
Example #25
Source File: GfshSignalHandler.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
protected SignalHandler getOriginalSignalHandler(final Signal signal) {
  final SignalHandler handler = originalSignalHandlers.get(signal);
  return (handler == SignalHandler.SIG_DFL || handler == SignalHandler.SIG_IGN ? null : handler);
}
 
Example #26
Source File: JUnit4RunnerTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public SignalHandler install(Signal signal, SignalHandler handler) {
  return null;
}
 
Example #27
Source File: JUnit4TestXmlListenerTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public void installHandler(Signal signal, SignalHandler signalHandler) {
  if (signal.getName().equals("TERM")) {
    handlers.add(signalHandler);
  }
}
 
Example #28
Source File: SunMiscSignalTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions = UnsupportedOperationException.class)
static void cannotHandleSIGIGN() {
    Signal signal = new Signal("INT");
    Assert.assertNotNull(SignalHandler.SIG_IGN, "SIG_IGN null; ");
    SignalHandler.SIG_IGN.handle(signal);
}
 
Example #29
Source File: SunMiscSignalTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions = UnsupportedOperationException.class)
static void cannotHandleSIGDFL() {
    Signal signal = new Signal("INT");
    Assert.assertNotNull(SignalHandler.SIG_DFL, "SIG_DFL null; ");
    SignalHandler.SIG_DFL.handle(signal);
}
 
Example #30
Source File: SignalHandlers.java    From bazel with Apache License 2.0 2 votes vote down vote up
/**
 * @see sun.misc.Signal#handle(sun.misc.Signal, sun.misc.SignalHandler)
 */
SignalHandler install(Signal signal, SignalHandler handler);