Java Code Examples for sun.misc.Signal#handle()

The following examples show how to use sun.misc.Signal#handle() . 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: InterpreterProcess.java    From submarine with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) throws InterruptedException, IOException {
  String interpreterType = args[0];
  String interpreterId = args[1];
  boolean onlyTest = false;
  if (args.length == 3 && StringUtils.equals(args[2], "test")) {
    onlyTest = true;
  }

  InterpreterProcess interpreterProcess = new InterpreterProcess(interpreterType, interpreterId, onlyTest);
  interpreterProcess.start();

  // add signal handler
  Signal.handle(new Signal("TERM"), signal -> {
    // clean
    LOG.info("handle signal:{}", signal);
  });

  interpreterProcess.join();
  System.exit(0);
}
 
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: BisqExecutable.java    From bisq with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void doExecute() {
    configUserThread();
    CoreSetup.setup(config);
    addCapabilities();

    Signal.handle(new Signal("INT"), signal -> {
        gracefulShutDown(() -> {
        });
    });

    Signal.handle(new Signal("TERM"), signal -> {
        gracefulShutDown(() -> {
        });
    });

    // If application is JavaFX application we need to wait until it is initialized
    launchApplication();
}
 
Example 4
Source File: Cptt12_LogWriter.java    From Zebra with MIT License 5 votes vote down vote up
/**
 * 测试信号捕获
 * @throws InterruptedException 
 */
public static void testLogWriter_2() throws InterruptedException{
	Thread logWriterThread=new LogWriteThread();
	logWriterThread.start();
	new GeneratorLogThread().start();	//
	new GeneratorLogThread().start();
	Thread.sleep(1000);
	Signal signal=new Signal("INT");	//程序结束信号,该信号可以被阻塞和处理
	Signal.handle(signal, new TerminateThread());
}
 
Example 5
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 6
Source File: HRegionServer.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * 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"), signal -> {
      conf.reloadConfiguration();
      cm.notifyAllObservers(conf);
    });
  }
}
 
Example 7
Source File: DefaultDebugFlow.java    From dew with Apache License 2.0 5 votes vote down vote up
@Override
protected void process(FinalProjectConfig config, String flowBasePath) throws ApiException, IOException {
    final Signal sig = new Signal(getOSSignalType());
    podName = PodSelector.select(config, Optional.ofNullable(podName));
    KubeHelper.inst(config.getId())
            .exec(podName, KubeDeploymentBuilder.FLAG_CONTAINER_NAME, config.getNamespace(),
                    new String[]{
                            "./debug-java.sh"
                    }, System.out::println);
    V1Service service = KubeHelper.inst(config.getId()).read(config.getAppName(), config.getNamespace(), KubeRES.SERVICE, V1Service.class);
    new KubeServiceBuilder().buildDebugPort(service, config.getApp().getDebugPort(), 5005);
    KubeHelper.inst(config.getId()).replace(service);
    service = KubeHelper.inst(config.getId()).read(config.getAppName(), config.getNamespace(), KubeRES.SERVICE, V1Service.class);
    System.out.println("Http-debug nodePort:["
            + service.getSpec().getPorts().stream().filter(v1ServicePort -> v1ServicePort.getPort().equals(5005))
            .map(V1ServicePort::getNodePort).collect(Collectors.toList()).get(0)
            + "].   Http-new nodePort: [" + service.getSpec().getPorts().stream().filter(v1ServicePort -> v1ServicePort.getPort().equals(9000))
            .map(V1ServicePort::getNodePort).collect(Collectors.toList()).get(0) + "]");
    System.out.println("==================\n"
            + "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005\n"
            + "==================");
    Signal.handle(sig, new ShutdownHandler(service, config));
    try {
        // 等待手工停止
        new CountDownLatch(1).await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: DecommissioningService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Inject
public DecommissioningService(Settings settings,
                              final ClusterService clusterService,
                              NodeSettingsService nodeSettingsService,
                              TransportSQLAction sqlAction,
                              TransportSQLBulkAction sqlBulkAction,
                              final TransportClusterHealthAction healthAction,
                              final TransportClusterUpdateSettingsAction updateSettingsAction) {
    super(settings);
    this.clusterService = clusterService;
    this.sqlAction = sqlAction;
    this.sqlBulkAction = sqlBulkAction;
    this.healthAction = healthAction;
    this.updateSettingsAction = updateSettingsAction;

    ApplySettings applySettings = new ApplySettings();
    applySettings.onRefreshSettings(settings);
    nodeSettingsService.addListener(applySettings);

    clusterService.add(new ClusterStateListener() {
        @Override
        public void clusterChanged(ClusterChangedEvent event) {
            removeRemovedNodes(event);
        }
    });
    try {
        Signal signal = new Signal("USR2");
        Signal.handle(signal, this);
    } catch (IllegalArgumentException e) {
        logger.warn("SIGUSR2 signal not supported on {}.", System.getProperty("os.name"), e);
    }
}
 
Example 9
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 10
Source File: SunSignalCatcher.java    From jsqsh with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a signal handler for handling Sun JVM signals.
 * 
 * @param manager The manager that created us.
 */
public SunSignalCatcher(SignalManager manager) {
    
    super(manager);
    Signal sig = new Signal("INT");
    Signal.handle(sig, this);
}
 
Example 11
Source File: Monitor.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Starts up all configured Metrics.
 *
 * @throws Throwable in case something goes wrong
 */
private void start() throws Throwable {

    // start Tor
    Tor.setDefault(new NativeTor(TOR_WORKING_DIR, null, null, false));

    Capabilities.app.addAll(Capability.TRADE_STATISTICS,
            Capability.TRADE_STATISTICS_2,
            Capability.ACCOUNT_AGE_WITNESS,
            Capability.ACK_MSG,
            Capability.PROPOSAL,
            Capability.BLIND_VOTE,
            Capability.DAO_STATE,
            Capability.BUNDLE_OF_ENVELOPES,
            Capability.REFUND_AGENT,
            Capability.MEDIATION);

    // assemble Metrics
    // - create reporters
    Reporter graphiteReporter = new GraphiteReporter();

    // only use ConsoleReporter if requested (for debugging for example)
    Properties properties = getProperties();
    if ("true".equals(properties.getProperty("System.useConsoleReporter", "false")))
        graphiteReporter = new ConsoleReporter();

    // - add available metrics with their reporters
    metrics.add(new TorStartupTime(graphiteReporter));
    metrics.add(new TorRoundTripTime(graphiteReporter));
    metrics.add(new TorHiddenServiceStartupTime(graphiteReporter));
    metrics.add(new P2PRoundTripTime(graphiteReporter));
    metrics.add(new P2PNetworkLoad(graphiteReporter));
    metrics.add(new P2PSeedNodeSnapshot(graphiteReporter));
    metrics.add(new P2PMarketStats(graphiteReporter));
    metrics.add(new PriceNodeStats(graphiteReporter));
    metrics.add(new MarketStats(graphiteReporter));

    // prepare configuration reload
    // Note that this is most likely only work on Linux
    Signal.handle(new Signal("USR1"), signal -> {
        try {
            configure();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    });

    // configure Metrics
    // - which also starts the metrics if appropriate
    configure();

    // exit Metrics gracefully on shutdown
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                // set the name of the Thread for debugging purposes
                log.info("system shutdown initiated");

                log.info("shutting down active metrics...");
                Metric.haltAllMetrics();

                try {
                    log.info("shutting down tor...");
                    Tor tor = Tor.getDefault();
                    checkNotNull(tor, "tor must not be null");
                    tor.shutdown();
                } catch (Throwable ignore) {
                }

                log.info("system halt");
            }, "Monitor Shutdown Hook ")
    );
}
 
Example 12
Source File: SigIntBarrier.java    From agrona with Apache License 2.0 4 votes vote down vote up
/**
 * Construct and register the barrier ready for use.
 */
public SigIntBarrier()
{
    Signal.handle(new Signal("INT"), (signal) -> signal());
}
 
Example 13
Source File: SignalLogger.java    From big-c with Apache License 2.0 4 votes vote down vote up
Handler(String name, LogAdapter LOG) {
  this.LOG = LOG;
  prevHandler = Signal.handle(new Signal(name), this);
}
 
Example 14
Source File: RegistererHelper.java    From inlein with Eclipse Public License 1.0 4 votes vote down vote up
static void dropSignal(String signame) {
    Signal.handle(new Signal(signame), dropper);
}
 
Example 15
Source File: SignalLogger.java    From hadoop with Apache License 2.0 4 votes vote down vote up
Handler(String name, LogAdapter LOG) {
  this.LOG = LOG;
  prevHandler = Signal.handle(new Signal(name), this);
}
 
Example 16
Source File: BookPubApplication.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 4 votes vote down vote up
public static void main(String[] args) {
    Reloader reloader = new Reloader();
    Signal.handle(new Signal("HUP"), reloader);
    SpringApplication.run(BookPubApplication.class, args);
}
 
Example 17
Source File: InterruptSignalHandler.java    From bazel with Apache License 2.0 4 votes vote down vote up
/** Disables SIGINT handling. */
public final synchronized void uninstall() {
  Preconditions.checkNotNull(oldHandler, "uninstall() already called");
  Signal.handle(SIGINT, oldHandler);
  oldHandler = null;
}
 
Example 18
Source File: SignalHandler.java    From flink with Apache License 2.0 4 votes vote down vote up
Handler(String name, Logger LOG) {
	this.LOG = LOG;
	prevHandler = Signal.handle(new Signal(name), this);
}
 
Example 19
Source File: DebugSignalHandler.java    From zstack with Apache License 2.0 4 votes vote down vote up
public static void listenTo(String name, ManagementNodeManagerImpl impl) {
    Signal signal = new Signal(name);
    Signal.handle(signal, new DebugSignalHandler(impl));
}
 
Example 20
Source File: ShutdownHandler.java    From ns4_gear_watchdog with Apache License 2.0 votes vote down vote up
/**
     * 方式一
     */
    public void registerSignal() {
        //注册关闭信号 -> TERM = 15 [kill -15 PID]
        Signal.handle(new Signal("TERM"), this);
        logger.info("WATCHDOG-进程服务注册关闭信号 TERM=15 [kill -15 PID]");
    }