0

I have written a script and it is working fine . It do some tail and grep operations. When I am closing my terminal and the greping the PID of my script , I can find the script is still present in the output of "ps -eaf |grep -i myScript.sh" . However I do not want this behaviour. I need to know , how can I handle such situation . I do not want to burden the CPU by my script. Please let me know. I searched google, and I mostly found about "How to keep the script running in background". but I was not able to get anything concreat about stopping it.

Thanks in advance.

user   9405 18803  0 07:32 pts/72   00:00:00 grep 29735
user  29735 11903  0 07:24 pts/30   00:00:00 sh myScript.sh
user  29818 29735  0 07:24 pts/30   00:00:00 tail -f --pid=29735 /var/log/message
user  29830 29735  0 07:24 pts/30   00:00:00 -csh
monk
  • 109
  • 2
  • 1
    Are you sure that what you're seeing in the ps output is the actual script, and not your grepping for it? – Jenny D Nov 30 '15 at 13:31
  • it is getting listed in ps -eaf , so I assume it is still breathing in background. – monk Nov 30 '15 at 13:33
  • What exactly is the output of `ps -eaf | grep -i myScript.sh`? – dr_ Nov 30 '15 at 13:35
  • user 9405 18803 0 07:32 pts/72 00:00:00 grep 29735 user 29735 11903 0 07:24 pts/30 00:00:00 sh myScript.sh user 29818 29735 0 07:24 pts/30 00:00:00 tail -f --pid=29735 /var/log/message user 29830 29735 0 07:24 pts/30 00:00:00 -csh – monk Nov 30 '15 at 13:44
  • I mainly wanted to know, if this is expected behaviour or kernel would/should take care of it ? – monk Nov 30 '15 at 13:45
  • That will depend on how the script was written and how it was called. – Jenny D Nov 30 '15 at 16:06

2 Answers2

2

Your script is run on another shell and uses the -f option (follow) of tail which appends the output as the file grows. In short, the script has no exit point, so it's not supposed to end, even if you desire the script to do so.

dr_
  • 1,085
  • 12
  • 19
1

tl;dr: create a bash exit hook and kill your background job from there.

Details:

  1. Create a PID file in your tail/grep script like so:

    echo $$ > $HOME/script.pid
    
  2. Add an exit hook to your login shell by adding something like this to your $HOME/.bash_profile :

    function finish {
      # Your cleanup code here
      kill -9 `cat $HOME/script.pid`
    }
    trap finish EXIT
    
  3. Profit.

This will break if you envoke your tail script multiple times. This could be handled by creating a lock file or skipping the script.pid file and crafting a killall <scriptname> inside the trap function.

chicks
  • 3,793
  • 10
  • 27
  • 36