J.E.Y
J.E.Y

Reputation: 1175

terminate a running program in the calling shell script

I wrote a shell script, A, in which it calls another script, B. What B does is to run some calculation and create a text file.

I don't own the code of B, and A has to call it in the foreground for non-tech reasons.

it takes less than 1 minute for B to calculate and create the text, however, B won't end itself and return the control to A until 6 minutes later.

Now the user complained why it takes 7 minutes to run script A.

Therefore my question is how can I rewrite A to detect the file is created and thus terminate B immediately to regain the control? if A still has to run B in foreground? is it doable?

hope I've made myself clear.

thanks! John

Upvotes: 1

Views: 44

Answers (1)

Teudimundo
Teudimundo

Reputation: 2670

This script calls in background a function that check whether the file exists, then using exec run the script with the same pid of the original script (such pid is obtained with $$), when the file is created the kill is sent to this pid and the exec'ed script is then killed:

#!/bin/bash
function checkAndKill {
    local pid=$1
    local filename=$2
    while [ ! -e $filename ]; do 
       sleep 1
    done
    kill $pid
}

checkAndKill $$ /path/of/the/file/to/check &

exec B.sh

Upvotes: 2

Related Questions