Terminating a process - is this code best practice?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Terminating a process - is this code best practice?
# 1  
Old 10-03-2016
Terminating a process - is this code best practice?

Hi Folks -

I am building a process to kill a list of services. Sometimes, there's a service that hangs therefore I need to add an additionla peice of code to kill all instances of a service if it exists.

Here is that portion of code:

Code:
echo ---------------------------------------------------------
echo "Terminate Hung Services"                               
echo ---------------------------------------------------------
_SERVICE=ESSSVR
  
ps -ef | grep ${_SERVICE} | awk '{print $2}' | xargs kill -9

My goal with the above piece of code is to kill any instances of ESSSVR.

Is that a correct way of going about it?

Thanks!
# 2  
Old 10-03-2016
Using signal 9 (= SIGKILL) directly is very bad.

Signals are a way of communicating with processes. And Signal 9 is a kind of non-communicating with which the processes get stopped immediately.

Most Software implement a proper cleanup when beeing told to terminate. All that cleanup can not take place here, because SIGKILL means the processes are stopped immediately by the operating system. That can cause a lot of trouble in your application, because Junk is not cleaned up(temporary files, temporary tables, proper setting some values in database done at a clean shutdown,...). Maybe your application will not start after you killed it that way once or some more times. Maybe your applications data will be corrupted badly over time.

A better way of doing what you want is send a signal 15 ( = SIGTERM), then give the task enought time time (10-60 Seconds depending on how much your application usually needs, to avoid trouble I would suggest you rather choose the 60 seconds). If the process is still alive afterwards send a signal 2 ( = SIGINT) and wait for another 10-60 seconds. If the process is still alive afterwards, finally kill it with signal 9 (SIGKILL).

Here's one of my scripts(could be improved though), doing this:

Code:
#!/bin/bash

function trim {

        arg="$*"
        shopt -s extglob
        arg="${arg#*( )}"
        arg="${arg%*( )}"
        echo "$arg"

}

function kill_soft_then_hard {

        PIDS="$*"

        PID_REGEX_PATTERN="^\s*("
        for pid in $PIDS;do
                PID_REGEX_PATTERN="$PID_REGEX_PATTERN|$pid"
        done
        PID_REGEX_PATTERN="$PID_REGEX_PATTERN)"

        # Here's the chain of signals being sent, when the processes refuse to terminate
        for SIGNAL in 15 1 3 7 9 ;do 
                kill -$SIGNAL $PIDS &>/dev/null
                for((w=1;$w<=30;w++)) ; do
                  if ps ax | grep -qE $PID_REGEX_PATTERN ; then
                          continue
                  else
                          break 2
                  fi
                  sleep 1
                done
        done

}

function kill_by_pattern {

        pattern="$1"
        PIDS="$(ps ax | grep "$pattern" | grep -v grep | awk '{print $1}')"
        PIDS="$(trim $PIDS)"

        [ -n "$PIDS" ] && kill_soft_then_hard $PIDS

}

kill_by_pattern ESSSVR

The programs pgrep and pkill may be useful too.

Have a look at the manpage signal(7) for a detailed explanation of the standard signals.

Last edited by stomp; 10-03-2016 at 01:14 PM.. Reason: Changed the script the you do not have to wait 30 secs if the process is already gone
This User Gave Thanks to stomp For This Post:
# 3  
Old 10-03-2016
Did you consider the killall command?
# 4  
Old 10-03-2016
Wow, thank you for that reply!

Is this the portion I add ESSSVR or is this just getting all processes then it find the pattern later?

Code:
PID_REGEX_PATTERN="^\s*("


Last edited by rbatte1; 10-04-2016 at 05:55 AM.. Reason: Added CODE tags
# 5  
Old 10-03-2016
Quote:
Originally Posted by SIMMS7400
Wow, thank you for that reply!

Is this the portion I add ESSSVR or is this just getting all processes then it find the pattern later?

PID_REGEX_PATTERN="^\s*("
No. I'm grepping the process list for multiple PIDs that may match the given pattern.

For normal use, you may just change the very last line of the script:

Code:
kill_by_pattern ESSSVR

If you like to tweak the script, the most liked improvement will be to do not wait the full 30 second period if the process is already terminated.

I recommend you to test the script in a testing environment before using it in production, since you do not know anything about my environment and vice versa for me.
This User Gave Thanks to stomp For This Post:
# 6  
Old 10-03-2016
Noted - thank you!

I will adjust and add your code to my script. And this would loop through and kill all instances of ESSSVR or just the first one it encounters?
# 7  
Old 10-03-2016
It'll kill all Instances that have ESSSVR in its name in the process list.
This User Gave Thanks to stomp For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Advanced & Expert Users

Close file descriptor without terminating process

Can any help me in finding the way to close opened file descriptor in Solaris ,without killing process. As accidently a file was removed which was opened by a process. Much thanks in advance :) (11 Replies)
Discussion started by: nitj
11 Replies

2. Shell Programming and Scripting

Cd error terminating loop

Hi All, I am trying to make a small shell script.In this it will got directory as per variable & run the find command on that directory.There are 120 + directories & not sure all of them are mounted.So the issue is if the directory doesent exists my loops gets terminated. so is there any was... (3 Replies)
Discussion started by: ajaincv
3 Replies

3. Shell Programming and Scripting

Best practice triggering a process?

Hi, Since I staterd working as Unix sysadmin (about 3 years ago) I always used to trigger a process evaluating the conditions needed to this process to be executed. Recently I've change the company where I work, and they usually create a trigger file to start a process or to stop a process while... (1 Reply)
Discussion started by: nefeli
1 Replies

4. Shell Programming and Scripting

How can i terminating expect script without terminating SSH connection.

Hi all , i know i ask a lot of question but these are really hard to solve and important question. I send two scripts: expect.sh: #!/usr/local/bin/expect spawn ssh root@172.30.64.163 expect "login:" send "root\n" expect "password:" send "root\n^M" interact and son.sh: ... (2 Replies)
Discussion started by: fozay
2 Replies

5. Shell Programming and Scripting

nohup terminating

hi all, i m running few batch process through shell script using nohup command but when session get terminated(due to network, reboot of desktop and closing session directly) all processes terminating abnormally and core file is generating. application batch process is connecting oracle... (4 Replies)
Discussion started by: arvindng
4 Replies

6. Shell Programming and Scripting

script unexpectedly terminating

I now that this isnt the greatest code around. Im a network guy by trade not a programer .. but needed something to compare config files ... Anyway ... intermittently, the program terminates. Ive been looking at the code for a week trying to figure it out and Im stumped. Can anyone provide... (0 Replies)
Discussion started by: popeye
0 Replies

7. HP-UX

Terminating Processes by Name

Hi! Just want to know if there is one command that I can use to kill processes by its name. Thanks. (1 Reply)
Discussion started by: love833
1 Replies

8. UNIX for Dummies Questions & Answers

Terminating child script with terminating the parent script

Hi I was working on a shell script with randomly shows a page of text from a randomly selected topic .As soon as the page is displayed it callers a timer script which keeps on running indefinitely until the timer script is killed by the user. This is where I have the problem,if I press... (2 Replies)
Discussion started by: mervin2006
2 Replies

9. Shell Programming and Scripting

terminating script with CTRL+D

Hi, I'm trying to make a script that reads the console input and terminates with CTRL+D. It's absolutely basic but I don't know how to "read" the CTRL+D. I've tried a bunch of things like EOT=^D while //with & without quotations do read input echo $input done while while ] ... (12 Replies)
Discussion started by: sanchopansa
12 Replies

10. UNIX for Dummies Questions & Answers

Terminating myself

just like what the subject said but the ip is different example if now my IP is 192.168.0.50 and my name is seed if i wanna terminate 192.168.0.55 with the same nick of mine, seed can i do that ?? and what is the command ?? (2 Replies)
Discussion started by: SeeD
2 Replies
Login or Register to Ask a Question