We help IT Professionals succeed at work.

C-shell script to kill process(s)

dkingsf
dkingsf asked
on
Don't know much about c-shell programming.  I need a c-shell or bourne shell script that can be run to check for a specific process name, AND owner and issue a kill -9 for that PID.  I'll award 200 points just because it's hard for me, but not necessarily for you.

Can't be perl or C by the way......
Comment
Watch Question

Commented:
The following command works on my system (solaris)

#!/bin/sh
kill -9 `ps -fU $1 | grep $2 | grep -v grep | grep -v the_name_of_this_script | awk '{print $2}'`
exit

Note the single quotes are backquotes prior to the ps and at the end of the command, the quotes around the awk print command are forward ticks.

You should test this by replacing the kill command with an echo command to make sure it works before using the kill command! :: Be careful - this script worked on my system - it may be different on yours due to fifferent versions of grep etc... ::

Also be aware that if you don't own the process being killed then you would need to be root user to run this script. There are a lot of security issues involved in letting non-root users have access to root permission scripts and this should never be done. If you need this functionality then really you should be using a setuid program rather than a script.

Cheers - Gavin

Commented:
Sorry - I should have mentioned that the command to run this script is as follows:

./the_script userid taskname


Cheers - Gavin
CERTIFIED EXPERT

Commented:
#!/bin/csh -f
if ($#argc < 2) then
    echo "Usage: $0 <username> <processname>"
    exit 1
endif
set os = `uname -s`
switch ($os)
  case 'SunOS':
     set pids = (`ps -ef|awk '($1=="'$1'"&&$9=="'$2'"){print $2};'`)
     breaksw
  case Linux:
     # NOTE that we assume that Linux uses gawk
     set pids = (`ps axu | awk '($1=="'$1'"&&$11=="'$2'"){print $2};'`)
     breaksw
  default:
     echo "**ERROR: unknown OS: $os"
     breaksw
endsw
if ($#pids > 0) then
    kill -9 $pids
else
    echo no matching processes
endif
CERTIFIED EXPERT

Commented:
No comment has been added lately, so it's time to clean up this Topic Area.
I will leave a recommendation for this question in the Cleanup topic area as follows:

- Points split newmang & ahoffmann

Please leave any comments here within the next 7 days

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

tfewster
Cleanup Volunteer

Commented:
Finalized as proposed

ahoffmann points at:
http://www.experts-exchange.com/Programming/Programming_Platforms/Unix_Programming/Q_20569250.html

modulo

Community Support Moderator
Experts Exchange

Explore More ContentExplore courses, solutions, and other research materials related to this topic.