2

I have a JavaScript React project, managed with yarn. I'd like to run it in the background, and be able to kill it from a script file. This needs to work on both Mac and Linux, and should not require su.

I've got this all working (so far, only tested on Mac), but am not 100% happy with my solution:

To launch:

    nohup yarn start > my.log 2>&1 &
    echo $! > my-pid.txt

Shutdown is uglier because killing the initial background process does not kill the process that actually runs the server. (Presumably, yarn spins off a few processes as it kicks off). The following code works, but feels really fragile to me. How can I improve it?

#!/bin/bash

# Shutdown background server

BASE_DIR=${BASH_SOURCE%/*}
source ${BASE_DIR}/scripts/utils.sh
cd $BASE_DIR

PIDFile="my-pid.txt"

if [ ! -f $PIDFile ]; then
    echo "Server pid not found"
    exit
fi

ROOT_PID=$(<"$PIDFile")

SON_PID=$(pgrep -P $ROOT_PID)
GRANDSON_PID=$(pgrep -P $SON_PID)

echo "Killing server processes: $ROOT_PID $SON_PID $GRANDSON_PID"

kill $GRANDSON_PID
rm "$PIDFile"

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
David Goldfarb
  • 1,796
  • 3
  • 18
  • 32

0 Answers0