Shell – Killing other user processes

killshell-scriptsignalsusers

There are certain user environments in which we have to login during certain performance testing and and kill all the process running in that environment.

The environment names are like rswrk01, … up to rswrk98.
and this is how we login.

sudo su - rswrk96

It doesn't prompt for any password and straightaway logs in.

Is it possible to automate a script for killing all the running processes in all the environments, instead of logging in manually and killing the processes?

I am not the root user by the way.

$ uname -a
HP-UX rcihp145 B.11.23 U 9000/800 3683851961 unlimited-user license

Best Answer

So rswrk01 and co are users. An occasionally-useful of kill is that if you pass -1 as the PID, the signal is sent to all processes that the signal sender has permission to send signals to. In other words, for a non-root user, kill -$sig -1 sends the signal to all processes running as that user. This includes the killer, but the delivery is atomic, so all concerned processes do get a signal.

Now all you have to do is put this in a loop, and you're done. Since formatting numbers with leading zeroes is a bit of a pain, a not very nice-looking but convenient trick is to put a leading 1 (i.e. count from 101 to 198 rather than 1 to 98) and strip that off.

i=101
while [ $i -le 98 ]; do
  sudo su - rswrk${i#1} kill -KILL -1
  i=$((i+1))
done

Or in ksh:

for ((i=101; i<=198; i++)); do
  sudo su - rswrk${i#1} kill -KILL -1
done

Or in bash or zsh:

for i in {01..98}; do
  sudo su - rswrk$i kill -KILL -1
done
Related Question