Home > Blockchain >  Java: How do I kill a background process automatically when the main application is stopped?
Java: How do I kill a background process automatically when the main application is stopped?

Time:01-06

I'm trying to use Java to launch a Gradle process that performs a continuous build in the background. Here is my code:

final var updateTimestampProcess =
      new ProcessBuilder("gradlew.bat", "compileGroovy", "--continuous")
                .directory(new File(System.getProperty("user.dir")))
                .inheritIO()
     try {
         updateTimestampProcess.start()
     } catch (IOException ignored) {}

It works, but the process doesn't terminate when I use IntelliJ's Stop command. I have to use Task Manager to hunt down the Java process that's running the gradlew command and end it manually.

How can I amend my code so that the background process it terminated when the main process stops?

CodePudding user response:

You can use a shutdown hook.

Add some code in the shutdown hook to kill the process you spawned.

Runtime
    .getRuntime()
    .addShutdownHook(new Thread(() -> System.out.println("killing the thing")));

Further Reading:

https://www.baeldung.com/jvm-shutdown-hooks

CodePudding user response:

If you want to use an external script to kill a process, I needed to do something similar not long ago. When I start my app, I write the PID to a file, and when I need to shut it down, I have this script reading that PID and then killing it:

#!/bin/bash

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PIDS_DIR="${SCRIPT_DIR}/pids/"

#
# Kills all the processes associated with a CWS ID
#
kill_cws() {
  if [ $# -ne 0 ]; then
    echo "ERROR: Invalid number of arguments. Expected 0."
    exit 1
  fi

  echo "[INFO] Stopping CWS..."

  for f in "${PIDS_DIR}/cws_"*".pid"; do
    kill_cws_process "${f}"
  done

  echo "[INFO] CWS Stopped"
}

#
# Kills a specific process
#
kill_cws_process() {
  local pid_file="$1"
  local pid
  pid=$(cat "${pid_file}")

  echo "[INFO][PID=${pid}] Killing CWS instance"
  kill -9 "${pid}"
  ev=$?
  if [ "${ev}" -ne 0 ]; then
    echo "[WARN][PID=${pid}] Error killing PID"
  fi

  echo "[INFO][PID=${pid}] Waiting for instance termination"

  echo "[INFO][PID=${pid}] Clean instance PID file"
  rm "${pid_file}"
  ev=$?
  if [ "${ev}" -ne 0 ]; then
    echo "[WARN][PID=${pid}] Error deleting pid file ${pid_file}"
  fi
}

#
# MAIN
#
kill_cws "$@"
  • Related