Search code examples
linuxbashshellbackground-process

A shell script (.sh) that calls an infinite loop called by another script to run in the background


Essentially what is happening is I'm operating on a limited instruction set framework (to run on an embedded device). The idea is very simple.

I call a script which makes two files:

  • file A: start_up - which calls the infinite loop
  • file B: background_while - which repeats a process over again

contents of file A:

#!/bin/sh
sh background_while&

contents of file B:

#!/bin/sh

while true
do
 #some commands
 sleep 5
done

I would like to terminate this process called in the background. Could someone show how this is best done using a keyboard interrupt?


Solution

  • If scriptA just ends after calling scriptB as a background then you cannot continue waiting for a keyboard interrupt. So, instead of immediately ending scriptA you can have a tight loop and wait for a signal, then kill your background processes by using trap.

    Something like:

    scriptA

    #!/bin/bash
    
    function kill_background(){
       kill ${myPid}
    }
    
    trap kill_background SIGINT
    
    bash ./scriptB.sh &
    myPid=$!
    
    wait
    

    Your scriptB will be the same. $! gets the pid of the last command executed (your scriptB) and wait makes scriptA wait for all background processes to return. trap will catch interrupt signals and kill your scriptB.