开发者

Unix script to kill a process after checking a condition several times and also run periodically

开发者 https://www.devze.com 2023-03-15 21:34 出处:网络
I want to write a unix shell script to run a command 3 times in every 80 seconds and write the every sequence in a different line in a text file. And also if the all results are 10 or more in a line I

I want to write a unix shell script to run a command 3 times in every 80 seconds and write the every sequence in a different line in a text file. And also if the all results are 10 or more in a line I want to kill the process:

for example:

pstack <pid> | grep -c 'abcd'

5

pstack <pid> | grep -c 'abcd'

5

pstack <pid> | grep -c 'abcd'

5

//Nothing to do.

//after 80 seconds again it runs:

pstack <pid> | grep -c 'abcd'

10 

pstack <pid> | grep -c 'abcd'

10

pstack <pid> | grep -c 'abcd'

10

kill -9 < PID>     // because all three outputs are bigger than开发者_开发问答 10   

also

the output file:

5 5 5 

10 10 10 

Note the if the output sequence is "10 10 11", "10 11 12" etc. then the process should be killed again. But if it is like "9 9 10" then no need to be killed.


What are you trying to achieve?

Sounds like an extremely hacky way to monitor a process. Couldn't you simply employ:

ulimit -T 10    # the maximum number of threads

or a variation (man bash , /ulimitEnter)?

That way a program could even possibly be more graceful in shutting itself down.


Note: since you suggest using kill -9 without trying other signals, perhaps you imply that signals never get handled? In that case you can probably use ulimit -i (the maximum number of pending signals)

Snippet

#!/bin/bash

function dumpstack()
{
    pstack $(pgrep a.exe) | grep -c abcd
}

while sleep 1; do dumpstack; done | tee rawoutput.log |
    {
        trap "" INT
        count=0;
        while read stackframes; do 
            if [[ $stackframes -lt 10 ]]; then
                count=0
            else
                count=$(($count+1))
            fi

            if [[ $count -ge 3 ]]; then
                echo KILL -9 !
                            break
            fi
            echo "(debug frames:$stackframes, count:$count)"
        done
    } | tee cooked_output.log
0

精彩评论

暂无评论...
验证码 换一张
取 消