sfedak
sfedak

Reputation: 676

Linux bash script that kills a process (not started by me) after x amount of time

I'm pretty inexperienced with Linux bash. That being said, I have a CentOS7 machine that runs a COTS application server. This application server runs other processes that sometimes hang. Since I have no control over the start of these processes, I'm looking for a script that runs every 2 minutes that kills processes of the name "spicer" that have been running for longer than 10 minutes. I've looked around and have only been able to find answers for processes that are run and owned by me.

I use the command ps -eo pid, command,etime | grep spicer to get all the spicer processes. The output of this command looks like:

18216 spicer -l/opt/otmm-10.5/Spi       14:20
18415 spicer -l/opt/otmm-10.5/Spi       11:49
etc...
18588 grep --color=auto spicer

I don't know if there's a way to parse this directly in bash. I'm also not well-versed at all in other Linux tools. I know that awk (or gawk) could possibly help.

EDIT

I have no control over the data that the process is working on.

Upvotes: 1

Views: 121

Answers (2)

hek2mgl
hek2mgl

Reputation: 157992

What about wrapping the executable of spicer and start it using the timeout command? Let's say it is installed in /usr/bin/spicer. Then issue:

cp /usr/bin/spicer{,.orig}
echo '#!/bin/bash' > /usr/bin/spicer
echo 'timeout 10m spicer.orig "$@"' >> /usr/bin/spicer

Another approach would be to create a cronjob defintion into /etc/cron.d/kill_spicer. Like this:

* * * * * root kill $(ps --no-headers -C spicer -o pid,etimes | awk '$2>=600{print $1}')

The cronjob will get executed minutely and uses ps to obtain a list of spicer processes that run longer than 10minutes and passes them to kill.

Probably you even want kill -9 if the process is hanging.

Upvotes: 3

David Z
David Z

Reputation: 131590

You can use the -C option of ps to select processes by name.

ps --no-headers -C spicer -o pid,etime

Then you can use cut to filter the results, if the spacing is consistent. On my system the pid field takes up 8 characters, so I'd use

kill $(ps --no-headers -C spicer -o pid,etime | cut -c-8)

If the spacing is inconsistent (but if so, what kind of messed up ps are you using? :-P), you can use awk { print $1 } instead of cut.

Upvotes: 0

Related Questions