Asynchronously monitor and interrupt a shell script

Viewed 110

I have a shell script that calls some data processing functions. These functions can be long-running. I want to update the script to interrupt the running process in case a certain "status" is seen from an external source. Otherwise the program should complete normally.

I have written a monitor_status function and called is asynchronously. The function sends a kill command to the main process in case the status is found. I have the following questions on this

  1. in case the kill -15 $ is invoked from monitor_status function, the cleanup function gets called twice. how can I prevent that?
  2. If the main process completes normally, how should I terminate the monitor_status function?

Also please suggest if there is a better way to handle such a scenario and any other improvements I can make to the script

The bash script looks something like this:

#!/bin/bash

function cleanup() {
  echo "cleanup invoked"
  if [[ -n "${child}" ]]; then
    echo "Stopping the child"
    kill "${child}" >/dev/null 2>&1 || true
  fi
  echo "cleanup done"
}

function main() { 
    echo "Starting main process"
    # do long running data processing
    echo "Exiting Main"
}

function monitor_status() { 
    echo "checking status"
    $Status = get_status
    if [[ $Status = "Terminate" ]]; then
        echo "Alert Alert!!!"
        kill -15 $$
    fi
    sleep 5
    done
}

monitor_status &
main &
trap cleanup SIGTERM EXIT
child=$!
wait "${child}"
0 Answers
Related