Kill All Processes Matching A Pattern In A Single Command
Introduction
Many times we write programs which runs many instances of itself, either while using fork or we manually run many copies of the same program, so during the development stage we may need to kill all running instances and modify the program and re-run, or there may be other situations where we may need to kill a ll perl programs running, etc etc. Till a few months back I used to do this job of killing manually process id by process id, like this
Code:
[root@pradeep test]# kill 31372
But recently I devised a command to kill all processes matching a pattern, I am sure someone else must have already done this, but there must any other to whom this might be helpful.
The Command
The command looks like this
Code:
ps ax|grep pl|awk '{print $1}'|xargs kill
Well, to some it might look confusing, let me break up the command a explain.
ps ax|grep pl
Returns all commands running which have 'pl' in them, so 'pl' is my pattern, you may write any pattern you want, here's the output of the command how it looks on my system.
Code:
[root@pradeep test]# ps ax|grep pl
31372 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31375 ? S 0:00 ./test.pl
31455 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31456 ? S 0:00 ./test.pl
31460 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31463 ? S 0:00 ./test.pl
31493 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31494 ? S 0:00 ./test.pl
31495 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31496 ? S 0:00 ./test.pl
31528 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31529 ? S 0:00 ./test.pl
31532 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31533 ? S 0:00 ./test.pl
31565 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31566 ? S 0:00 ./test.pl
31569 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31570 ? S 0:00 ./test.pl
31603 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31604 ? S 0:00 ./test.pl
31607 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31608 ? S 0:00 ./test.pl
31635 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31636 ? S 0:00 ./test.pl
31639 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31640 ? S 0:00 ./test.pl
31670 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31671 ? S 0:00 ./test.pl
31672 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31673 ? S 0:00 ./test.pl
31674 ? Ss 0:00 /bin/sh -c cd /home/pradeep/test ; ./test.pl
31675 ? S 0:00 ./test.pl
31681 ? S 0:00 ./test.pl
31686 ? S 0:00 ./test.pl
31693 ? S 0:00 ./test.pl
31699 pts/0 R+ 0:00 grep pl
awk '{print $1}'
Prints the first column returned by the previous command, in this case the PID e.g. - 31671
xargs kill
Use xargs to pass the PID printed by the previous command to kill command
I hope this is helpful.
|