Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Shell script to use KILL command!! New to shell scripting......Urgent!!

Posted on 2006-06-06
50
Medium Priority
?
787 Views
Last Modified: 2013-12-26
Hi iam new to UNIX world...I need to write a shell script for the following scenario...
I issue TOP command to list out the processes that are running.I need to monitor these processes and check for the process that is using cpu time more and i need to issue KILL command for that PID.The time limit that iam restricting my process is 30min.If the process uses more that 30 mins then i need to kill that process...
The screen output on my console looks like this:


 09:46:30  up 2 days, 23:27,  2 users,  load average: 0.00, 0.05, 0.22
73 processes: 72 sleeping, 1 running, 0 zombie, 0 stopped
CPU states:  cpu    user    nice  system    irq  softirq  iowait    idle
           total    0.1%    0.0%    0.2%   0.0%     0.0%    0.0%   99.5%
           cpu00    0.0%    0.0%    0.0%   0.0%     0.0%    0.0%  100.0%
           cpu01    0.0%    0.0%    1.0%   0.0%     0.0%    0.0%   98.9%
           cpu02    0.0%    0.0%    0.0%   0.0%     0.0%    0.2%   99.7%
           cpu03    0.4%    0.0%    0.0%   0.0%     0.0%    0.0%   99.5%
Mem:  4119992k av, 3867856k used,  252136k free,       0k shrd,  187076k buff
                   2864524k actv,  145476k in_d,   74300k in_c
Swap: 3598476k av,     996k used, 3597480k free                 2925240k cached

  PID        USER           PRI         NI         SIZE        RSS       SHARE       STAT       %CPU       %MEM   TIME       CPU       COMMAND
 1514       root            16         0        5140       5140         996       S           0.2        0.1        15:00         1       dcstor32d
 4559       root            25         0        319M       319M        1992       S           0.1        7.9         7:27         1       java


Now i need to see the time taken by the command and kill that command with its PID(if the time is more than 30min)

Please help me with the script code for the above problem
0
Comment
Question by:raghuudupa
  • 26
  • 22
  • 2
50 Comments
 
LVL 3

Expert Comment

by:root_start
ID: 16847716
Hi raghuudupa,

In the following script I use the "top" command, and it kills all process that has more than maxCPUTime of CPU usage.
===================================================================================================
#!/bin/sh

maxCPUTime=30
show=0
processListFile="processFile.tmp"

echo "Generating Process List to file: [${processListFile}]..."
top -n 100 -d 1 -f ${processListFile}

cat ${processListFile} | while read cpu tty pid username pri ni size res state time wcpu cpu command
do
      if [ ${show} -eq 1 ]
      then
            # echo "Time: $time"
            min=`echo ${time} | cut -f1 -d":"`
            # echo "CPU Minutes: [${min}]."
            if [ ${min} -ge ${maxCPUTime} ]
            then
                  echo "Killing process Id: [${pid}] - CPU Minutes: [${min}]."
                  kill -15 ${pid}
            fi
      fi
      
      if [ ! -z "${time}" ]
      then
            if [ ${time} = "TIME" ]
            then
                  show=1
            fi
      fi
done
===================================================================================================

I hope it helps you. =0)
0
 
LVL 3

Expert Comment

by:root_start
ID: 16847734
Ops I forgot one thing: to remove the file after the script finishes. Add the following line to the end of the script:

rm -f  ${processListFile} 2>> /dev/null

=0)
0
 
LVL 3

Expert Comment

by:root_start
ID: 16847762
Ops... one more thing to change... =0)

I created the script in my machine and I forgot to check your "top" output.

Also change the line:
cat ${processListFile} | while read cpu tty pid username pri ni size res state time wcpu cpu command

To

cat ${processListFile} | while read pid user pri ni size rss share stat pcpu pmem time cpu command

Let me know if you have problems. =0)
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:raghuudupa
ID: 16847895
I did not follow the changes...To be frank i have to just use the script as i do not have unix shell script idea...If you do not mind can you give me the script with the changes you made later.Plz..
Once it works i will give you the points  :-)
0
 

Author Comment

by:raghuudupa
ID: 16848172
yeah i made the changes and i will try to use this script and get back to you...Appreciate your help...Dont worry about the points and grade...I owe u ...that anyway...:-)
0
 
LVL 48

Expert Comment

by:Tintin
ID: 16848347
root_start.

What version of top do you use?  Versions I have running on Redhat, Solaris and Freebsd don't have the -f flag.

raghuudupa.

Assuming you are on a Linux system, you don't need use top, ps will work just as well, eg:

#!/bin/sh
ps -e -opid,time | sed 1d| while read pid time
do
  hour=`echo $time|cut -f1 -d:`
  min=`echo $time|cut -f2 -d:`
  [ $hour -gt 0 -o $min -ge 30 ] && kill $pid
done

If you are on a non-linux system, then the time fields are in min:sec rather than hour:min:sec, so it's a simple adjustment to make.

0
 

Author Comment

by:raghuudupa
ID: 16848446
hi tintin,
  iam using linux.....Linux RH AS3
I dont have a clue on wht your code is but i guess you have understood my problem....So assuming you did do i have to use only the piece of code you have written as the shell script?? Please advice as iam a novice in this area....
It would be great if you give the script so that all i have to do it is run it!!!
I hope you understood my difficulty in UNIX area!!
0
 
LVL 48

Expert Comment

by:Tintin
ID: 16848756
The script I provided is complete and will run on Linux RH AS3.

Just copy the contents to a file, for example 'killtime', then do

chmod +x killtime

Then to run, type in

/path/to/killtime

Probably best to put the script in /usr/local/bin, so that it should be in your PATH, then you need to just type in 'killtime'

Remember that you'll need to run this as root, otherwise you won't have permissions to kil the process.

Also, *why* do you want to do this?  What problem are you trying to solve?
0
 

Author Comment

by:raghuudupa
ID: 16848867
Hey let me thnk you first...Actually iam trying to monitor the load process on the server..The moment a process is taking more than 30mins iam supposed to kill the process.So i was doing this manually.Now the management wants to automate the process and asked me to write a shell script which i did not know how to write!
The moment i type TOP command iam listed out with the process along with the details of cpu usage and other stuff.I am supposed to see which of the process is taking more than 30 mins and execute the KILL PID command...This is required because there is some data loading stuff going on an application ..so to ease out the load on the server we are doing this...
Hope this answers yur question..I will get back once i use this script successfully..
Thanks
0
 
LVL 3

Expert Comment

by:root_start
ID: 16851250
Hi raghuudupa,

I didn't know that you were executing it in a Linux box, and as Tintin said, the "-f" option does not exists in the Linux version of "top". When I created the script, I used a HP-UX.

If someonelse tries to use the script Tintin provided, be careful because if "ps" is not "XPG4" compatible, the "-o" option is not available. To enable "XPG4", check the link: http://www.jroller.com/page/sgm?entry=hp_ux_xpg4

This is from "man ps" in a HP-UX box:
================================================================================
           -o format      (XPG4 Only.) format is a comma- or space-separated
                          list of the columns to display, in the order they
                          should be displayed.  (Valid column names are
                          listed below.)  A column name can optionally be
                          followed by an equals sign (=) and a string to use
                          as the heading for that column.  (Any commas or
                          spaces after the equals sign will be taken as a
                          part of the column heading; if more columns are
                          desired, they must be specified with additional -o
                          options.)  The width of the column will be the
                          greater of the width of the data to be displayed
                          and the width of the column heading.  If an empty
                          column heading is specified for every heading, no
                          heading line will be printed.  This option
                          overrides options -c, -f, -j, -l, -z, and -P; if
                          they are specified, they are ignored.
================================================================================

I hope it helps. =0)
0
 
LVL 3

Expert Comment

by:root_start
ID: 16851671
Hey raghuudupa and Tintin,

You don't need to specify the "-o" option in "ps".

Check below:
===============================================================
ps -ef | sed 1d | while read uid pid ppid c stime tty time cmd
do
        hour=`echo $time | cut -f1 -d":"`
        min=`echo $time | cut -f2 -d":"`
        if [ $hour -gt 0 -o $min -ge 30 -a $pid -ne 0 ]
        then
               echo "Killing process: [$pid] - Time: [$time]."
               kill -15 $pid
        fi
done
===============================================================

I hope it helps you. =0)
0
 

Author Comment

by:raghuudupa
ID: 16851927
Dear  root_start,

>>ps -ef | sed 1d | while read uid pid ppid c stime tty time cmd

In the above line it seems the cols that you are reading does not match with the column output of my console..Am i right??
wht are uid ppid c stime tty ???
Is it not enough if we read only the PID,TIME and COMMAND???

The thing is my knowledge about this whole UNIX shell script is 0....:-)
So iam going blindly by what you guys are saying..
Apologies for that!!

0
 

Author Comment

by:raghuudupa
ID: 16852119
what is the line kill -15 $pid for??
0
 

Author Comment

by:raghuudupa
ID: 16852600
Iam sorry folks

 i forgot to mention one thing...
I need to kill a process whose time is more than 30min and iam looking at one particular command and that is LoadEricssonSta.This command usually sometimes uses more than 30:00 in the time column and when that happens i should kill that PID..

 PID       USER          PRI        NI        SIZE       RSS      SHARE      STAT      %CPU      %MEM   TIME      CPU      COMMAND

1514      root           16           0         5140      5140        996           S          0.2           0.1       45:00        1      LoadErricsonSta

The earlier one that you suggested will kill all processes which go above 30 mins and tht would be disastrous..Sorry about that folks..
Would be really nice of you if you rescript the shell script...

Sorry once again.!!
:-)
0
 
LVL 3

Expert Comment

by:root_start
ID: 16852649
Please, put here the output of the following command:

ps -ef | head -10
0
 
LVL 3

Expert Comment

by:root_start
ID: 16852689
I read your comment above, and let me see if I understood correctly: you just want to kill the process "LoadErricsonSta" or you don't want this one to be killed?
0
 

Author Comment

by:raghuudupa
ID: 16852888
Hey Mate,
I just want to kill the process called LoadErricsonSta....
Where do u want me to execute the command
ps -ef | head -10..??
After i execute TOP???and where the processes are being monitored??
FYI i dont have root permission...
My PM just wants me to write the script for the kill command for that process!!!

The output on the console when i issue TOP command is like this

  PID  USER     PRI  NI  SIZE   RSS SHARE STAT %CPU %MEM   TIME CPU COMMAND
 7659  root      15   0  5752   5752  4824    S     0.7        0.1     166:55   1  magicdev
 7665  root      25  10 13224  12M  8760   S N   0.3         0.3      96:22   1  rhn-applet-gui
 6289  root      16   0  7864   7864  3756   S     0.2         0.1      69:05    0  dcstor32d
32377  root      25   0 86216  84M 12520   S     0.2         2.0      34:55     1 LoadEricssonSta

Hope this helps!!
 6608  root      25   0  2792   2792  1776    S     0.1        0.0       13:57   0  dcsnmp32d
     
0
 
LVL 3

Expert Comment

by:root_start
ID: 16852993
If you are not root, you will not be able to kill that process, because only the owner and the superuser(root) can kill a process.

I mean, as root is the owner of that process, only root can kill it.

If you are root, you can use the following to kill that automatically:
ps -ef | grep LoadEricssonSta | grep -v grep | awk '{print $2}' | xargs kill
0
 

Author Comment

by:raghuudupa
ID: 16853027
Yeah you are right...But now i dont have root permission as iam new to this job and iam going to get it soon...
I need to give them the script today for the kill process.....So whatever script you have written earlier will it stand good??
Can you please modify it for the LoadEricssonSta and give me...so that i can submit it..
0
 
LVL 3

Expert Comment

by:root_start
ID: 16853045
If you only want to kill that when it uses more than 30 minutes of CPU, you can use the following:
===============================================================
ps -ef | grep LoadEricssonSta | grep -v grep | while read uid pid ppid c stime tty time cmd
do
        hour=`echo $time | cut -f1 -d":"`
        min=`echo $time | cut -f2 -d":"`
        if [ $hour -gt 0 -o $min -ge 30 ]
        then
               echo "Killing process: [$pid] - Time: [$time]."
               kill -15 $pid
        fi
done
===============================================================
0
 

Author Comment

by:raghuudupa
ID: 16853107
Could you throw some light on what uid,ppid,c,stime,tty, are??
They dont look similar to the column output on the console!!
Just for knowledge sake i want to know so that i can work on it at a laterstage.

Thanks any way for the help ..I will get back to you if i need more help
Let me see if this thing gets okayed!!(Wont forget to give you points  :-)) once it works..

0
 
LVL 3

Expert Comment

by:root_start
ID: 16853131
uid,ppid,c,stime,tty are the columns returned by the command: "ps -ef", try "man ps", and they don't look similar because I am not using "top".
0
 

Author Comment

by:raghuudupa
ID: 16853148
Ok thanks root_start...I hope this script of yours works..Iam fwding it to my PM ...Let us see...
Thanks once again...I appreciate your help..
0
 

Author Comment

by:raghuudupa
ID: 16853210
can we not use top command and write similar script??
Just for info sake iam asking...
0
 
LVL 3

Expert Comment

by:root_start
ID: 16853447
Sorry, but why do you want to use "top"?
It is possible to write one, but the script would be a little bit complicated.
0
 

Author Comment

by:raghuudupa
ID: 16853535
ok fine...I just saw the man -ps command and i understood it gives me a snapshot(latest)..I guess that serves my purpose..
What is the kill -15$pid doing?Why the no: 15??
I know this is not a tutorial for unix but i guess you dont mind  :-)
Thanks
0
 
LVL 3

Expert Comment

by:root_start
ID: 16853601
Ok.
The command: "kill -15 <pid>" mean that the process will finish normally, but if you want it to be killed abort, just use, "kill -9 <pid>".
Also try: "man kill" or "kill -l", in the last one you will see all types of kill you have.
0
 
LVL 3

Expert Comment

by:root_start
ID: 16853624
Try to read the following, it will give you a better idea: http://www.decf.berkeley.edu/help/unix/kill.html
0
 

Author Comment

by:raghuudupa
ID: 16853646
Thanks i appreciate it...
0
 

Author Comment

by:raghuudupa
ID: 16853713
i have to type it in note pad and save it as .sh file is it??For example Kill.sh
0
 
LVL 3

Expert Comment

by:root_start
ID: 16853761
Yes... you can copy and paste.

You can use as filename: killLoadEricssonStaProcess.sh
====================================================================
#!/bin/sh

ps -ef | grep LoadEricssonSta | grep -v grep | while read uid pid ppid c stime tty time cmd
do
        hour=`echo $time | cut -f1 -d":"`
        min=`echo $time | cut -f2 -d":"`
        if [ $hour -gt 0 -o $min -ge 30 ]
        then
               echo "Killing process: [$pid] - Time: [$time]."
               kill -15 $pid
        fi
done
====================================================================
0
 

Author Comment

by:raghuudupa
ID: 16853791
Gr8!!!!!!!!Thanks for the help.once again....thanks  :-)
0
 

Author Comment

by:raghuudupa
ID: 16855565
Hey thanks for the help root_start,
  The script you sent me worked fine i believe ..But my PM wants me to write the all kill logs to a file...and not Echo....
He also wants me to setup a cron on the machines...I dont know what that means......
I would appreciate if you help me out with this ...
0
 
LVL 3

Expert Comment

by:root_start
ID: 16855784
The script with the log is:
====================================================================
#!/bin/sh

outputLogFile="/tmp/logKillLoadEricssonSta.log"
logDate=`date +'%Y%m%d %H%M%S'`

ps -ef | grep LoadEricssonSta | grep -v grep | while read uid pid ppid c stime tty time cmd
do
        hour=`echo $time | cut -f1 -d":"`
        min=`echo $time | cut -f2 -d":"`
        if [ $hour -gt 0 -o $min -ge 30 ]
        then
               echo "Date: [${logDate}] -> Killing process: [$pid] - Time: [$time]." >> ${outputLogFile}
               kill -15 $pid
        fi
done
====================================================================

About the cron job, take a look to the following link: http://www.unixgeeks.org/security/newbie/unix/cron-1.html

Reading you will learn how it works. =0)
0
 

Author Comment

by:raghuudupa
ID: 16855917
Cool job mate,
  Gr8 help i appreciate it....
Thanks a ton..
0
 

Author Comment

by:raghuudupa
ID: 16869514
Hi root_start,
  The script has been okayed but they want me to do some changes...If you could help me out with this it will be great!!!!!!!!!!

They want me to do the following things:

1)Change the name to include the full script name.
2)In the script grep for the full script name

Please tell me how to do the above things...

Thanks
0
 
LVL 3

Expert Comment

by:root_start
ID: 16869927
Hey... sorry, but I didn't understand your requirements.
0
 

Author Comment

by:raghuudupa
ID: 16869959
Ok wht ever scrip you gave worked fine i believe...I did not test it but the team said it is ok....
I named the script as killLoadEricssonStaProcess.sh

They want me change the name to include the full script name( idont know wht that means)
In the script grep for the full script name ..

I guess you understood...Else i will take the requirement in an elaborate manner again...

Thanks
0
 
LVL 3

Expert Comment

by:root_start
ID: 16870453
I think I understood now. =0)

What is the full name of the process? LoadEricssonSta???

I think this is what they are asking to add to the script.
0
 

Author Comment

by:raghuudupa
ID: 16870589
When iam issuing top command the name that iam supposed to look for is LoadEricssonSta...
Now how do i add that to the script??
I thought we already did that in the script you furnished me with??
If there is any change please tell me so that i can incorportate accordingly!
Thanks once again
0
 
LVL 3

Expert Comment

by:root_start
ID: 16870686
Please, execute the following command and post the result here.

ps -efx | grep LoadEricssonSta | grep -v grep
0
 

Author Comment

by:raghuudupa
ID: 16870763
Its not printing anything...Guess i should have root permissions to see that
But i can issue the Top command and see the name and tell u
Is it ok
But when i am issuing only ps -efx | grep LoadEricssonSta
iam getting
29386 pts/0    S      0:00  \_ grep LoadEricssonSta HOSTNAME=WEP.localdomain TER                                                                             M=xterm SHELL=/bin/bash CATALINA_HOME=/usr/tomcat HISTSIZE=1000 SSH_CLIENT=10.16                                                                             .26.51 3510 22 SSH_TTY=/dev/pts/0 USER=raghu LD_LIBRARY_PATH=/home/oracle/produc                                                                             ts/10g/instantclient_10_2/lib LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:s
0
 
LVL 3

Expert Comment

by:root_start
ID: 16870853
Hey... the script I sent you is correct.
0
 

Author Comment

by:raghuudupa
ID: 16870900
Ok i will take wht you say and i appreciate your help
...But i dont know wht they want ???
What they mean by saying
1)Change the name to include the full script name.
2)In the script grep for the full script name
iam unable to follow..I have asked them to describe elaborately wht they actually want?

What do they mean by greping the fullscript name??
0
 
LVL 3

Expert Comment

by:root_start
ID: 16871318
I thought they were asking to grep the full process name, but this is what the script is doing.
0
 

Author Comment

by:raghuudupa
ID: 16871366
The script you sent is absolutely fine....This is what my TL says:

The script itself looks good. A couple of points.

- Change the name to include the full script name.
- In the script grep for the full script name

I dont know what that means??
Do we have to include the name of the process too ??
Like including [$cmd]  in the script? to get the name of the process ?

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
echo "Date: [${logDate}] -> Killing
process: [$cmd] - process id: [$pid] -
Time:
[$time]." >> ${outputLogFile}
0
 
LVL 3

Expert Comment

by:root_start
ID: 16871411
If think can be this, add the $cmd to the log.
0
 

Author Comment

by:raghuudupa
ID: 16871528
I did not get you ...U mean i should go ahead with the following script??


#!/bin/sh

outputLogFile="/tmp/logKillLoadEricssonSta.log"
logDate=`date +'%Y%m%d %H%M%S'`

ps -ef | grep LoadEricssonSta | grep -v grep | while
read uid pid ppid cmd
c
stime tty time cmd
do
        hour=`echo $time | cut -f1 -d":"`
        min=`echo $time | cut -f2 -d":"`
        if [ $hour -gt 0 -o $min -ge 30 ]
        then
               echo "Date: [${logDate}] -> Killingprocess: [$cmd] - process id: [$pid] - Time: [$time]." >> ${outputLogFile}
               kill -15 $pid
        fi
done

0
 
LVL 3

Accepted Solution

by:
root_start earned 1000 total points
ID: 16871734
yes... that's correct.
0
 

Author Comment

by:raghuudupa
ID: 16871785
Ok i will send this across and also wait for their reply to my mail asking them for an elaborate req...

Thanks for the help and will bother you if i need to and hopefully this issue should not drag on for a long time...
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual …
Introduction: Dialogs (2) modeless dialog and a worker thread.  Handling data shared between threads.  Recursive functions. Continuing from the tenth article about sudoku.   Last article we worked with a modal dialog to help maintain informat…
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question