sun.misc.Signal Java Examples

The following examples show how to use sun.misc.Signal. 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: JStormSignalHandler.java    From jstorm with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #3
Source File: SunMiscSignalTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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; ");
        }
    }
}
 
Example #4
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 #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: DistheneReader.java    From disthene-reader with MIT License 6 votes vote down vote up
@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);
}
 
Example #7
Source File: DistheneReader.java    From disthene-reader with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #8
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 #9
Source File: GraceKillSignalHandler.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@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());
						});
}
 
Example #10
Source File: GraceKillSignalHandler.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@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);
		});
	});
}
 
Example #11
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 #12
Source File: SignalHandler.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Inject
public SignalHandler(ActorSystem actorSystem, Provider<Application> applicationProvider) {
  Signal.handle(
      new Signal("TERM"),
      signal -> {
        isShuttingDown = true;
        ProjectLogger.log(
            "Termination required, swallowing SIGTERM to allow current requests to finish",
            LoggerEnum.INFO.name());
        actorSystem
            .scheduler()
            .scheduleOnce(
                STOP_DELAY,
                () -> {
                  Play.stop(applicationProvider.get());
                },
                actorSystem.dispatcher());
      });
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
Source File: JUnit4TestXmlListenerTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void signalHandlerWritesXml() throws Exception {
  TestSuiteModelSupplier mockModelSupplier = mock(TestSuiteModelSupplier.class);
  TestSuiteModel mockModel = mock(TestSuiteModel.class);
  CancellableRequestFactory mockRequestFactory = mock(CancellableRequestFactory.class);
  OutputStream mockXmlStream = mock(OutputStream.class);
  JUnit4TestXmlListener listener = new JUnit4TestXmlListener(
      mockModelSupplier, mockRequestFactory, fakeSignalHandlers, mockXmlStream, errPrintStream);

  Request request = Request.classWithoutSuiteMethod(PassingTest.class);
  Description suiteDescription = request.getRunner().getDescription();

  when(mockModelSupplier.get()).thenReturn(mockModel);

  listener.testRunStarted(suiteDescription);
  assertThat(fakeSignalHandlers.handlers).hasSize(1);

  fakeSignalHandlers.handlers.get(0).handle(new Signal("TERM"));

  String errOutput = errStream.toString(CHARSET);
  assertWithMessage("expected signal name in stderr")
      .that(errOutput.contains("SIGTERM"))
      .isTrue();
  assertWithMessage("expected message in stderr")
      .that(errOutput.contains("Done writing test XML"))
      .isTrue();

  InOrder inOrder = inOrder(mockRequestFactory, mockModel);
  inOrder.verify(mockRequestFactory).cancelRun();
  inOrder.verify(mockModel).testRunInterrupted();
  inOrder.verify(mockModel).writeAsXml(mockXmlStream);
}
 
Example #18
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 #19
Source File: ConfigReloadOnHup.java    From esigate with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Signal signal) {
    if (SIGNAL_NAME.equals(signal.getName())) {
        LOG.warn("Signal " + SIGNAL_NAME + " received. Reloading configuration.");
        DriverFactory.configure();
    }

}
 
Example #20
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 #21
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 #22
Source File: JUnit4TestXmlListener.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Signal signal) {
  try {
    errPrintStream.printf("%nReceived %s; writing test XML%n", signal.toString());
    requestFactory.cancelRun();
    model.testRunInterrupted();
    model.writeAsXml(xmlStream);
    errPrintStream.println("Done writing test XML");
  } catch (Exception e) {
    errPrintStream.println("Could not write test XML");
    e.printStackTrace(errPrintStream);
  }
}
 
Example #23
Source File: SignalLogger.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #24
Source File: ReaperApplication.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
private void addSignalHandlers() {
  if (!System.getProperty("os.name").toLowerCase().contains("win")) {
    LOG.debug("adding signal handler for SIGHUP");
    Signal.handle(new Signal("HUP"), signal -> {
      LOG.info("received SIGHUP signal: {}", signal);
      reloadConfiguration();
    });
  }
}
 
Example #25
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 #26
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 #27
Source File: Cptt12_LogWriter.java    From Zebra with MIT License 5 votes vote down vote up
@Override
public void handle(Signal arg0) {
	System.out.println("系统中断....");
	int n=0;
	while(!logs.isEmpty()){
		try {
			System.out.println("睡眠 "+(++n)+" 次");
			Thread.sleep(500);
		} catch (InterruptedException e) {
			System.out.println("钩子进程请求中断...");
		}
	}
	System.out.println("系统中断完毕....");
	System.exit(-1);
}
 
Example #28
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 #29
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 #30
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);
    }
}