Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Automatically kill a function after unexpected end of calling script

Status
Not open for further replies.

TSch

Technical User
Jul 12, 2001
557
DE
Hi folks,

here we go again ...

I'm using something like this:

Code:
function dosomething
{
while :;
do
  ps -ef | something
  echo "Something more"
done
}

dosomething &
function_pid=$!

"some other actions"
..
..
..

kill $function_pid

So far so good. But whenever the main script ends unexpectedly or just by pressing <STRG>+<C> the dosomething function remains active and (in this case) continues to fill the screen with stupid echo outputs ... ;-)

Is there any way to automatically end the function in such a case ?

My first idea was do include something like this in the function itself:

Code:
active=$(ps -ef | grep Main_Script | grep -v grep | wc -l)
if [ $active -eq 0 ];
then
exit

But after pressing <STRG>+<C> the main script seems to end but a process containing the name of this main script remains active and therefore the functions is always going to find 1 line using the ps command ...

Any ideas how so solve this problem ?

Regards
Thomas
 
Look into the trap facility which allows you to do some cleanup when the script has been interrupted by certain signals, one of which is interruption via Ctrl-C.

Annihilannic.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top