How to propagate a signal through a collection of scripts?

后端 未结 4 1626
Happy的楠姐
Happy的楠姐 2020-12-15 18:14

I have an collection of scripts which are controlled by a main one. I want to trap the signal ctrl+c in the main script and propagate it to the others.

4条回答
  •  自闭症患者
    2020-12-15 18:40

    MAIN PARENT SCRIPT HEADER BEFORE THE MAIN LOOP:::

    #Catch control-c and clean up testd instances if necessary
    cleanup () {
        clear
        echo "Caught Signal.  Shutting Down MAIN."
        if [ "$MAIN_on" -eq 1 ]
        then
        M_shutdown
        fi
        exit 1
      }
    

    In the main body of the script, as you spawn subprocesses you maintain an array with the proc ids of each. To load the PID into the array set the value to last spawned process e.g. put the following after each sub-shell spawn.

    proc_id_array[1]=$!
    

    Contents of the M_shutdow would be something like...

    M_shutdown () {
    
        if [ "$MAIN_on" -eq 1 ]
        then
        echo "Stopping Main"
        echo "shutting down active subscripts"
        count_proc_id=1
    
    
    while [ "$count_proc_id" -lt "$max_proc_id" ]
            do
    
                kill ${proc_id_array[$count_proc_id]} > /dev/null 2>&1
                DATE=$(date +%m%d%y-%k:%M)
                echo "$DATE: ${proc_name_array[$count_proc_id]} \(PID: ${proc_id_array[$count_proc_id]}\) stopped." >> $logfile             
                proc_id_array[$count_proc_id]="A"
                count_proc_id=`expr $count_proc_id + 1`
            done
    
    
            echo "MAIN stopped"
            MAIN_on=0
    
            sleep 5
            else
            echo "MAIN already stopped."
            sleep 1
            fi
        }
    

提交回复
热议问题