Score:0

How monitor open files and kill its PID by shell script?

fr flag

My system gets me an error that saying 'Too many open files'. I investigated this error and turned out that /usr/bin/uwsgi created sockets(?) more than 1020. If it creates more than 1020, I guess, the above error comes up with.

So What I try to do is to run a shell script that monitors the number of open files and if it exceeds more than 1000, to kill its PID to resolve this error at this stage.

#uwsgimonitor.sh
#!/bin/bash

#filename=/usr/bin/uwsgi

filename=/usr/bin/uwsgi
Cnt= lsof | awk '/uwsgi/ {print $1,$2}' | uniq -c | sort -r | head -1 | awk '{print $1}'
PROCESS_ID = lsof | awk '/uwsgi/ {print $1,$2}' | uniq -c | sort -r | head -1 | awk '{print $2}'

if [ $Cnt gt 1000 ]
then
    echo "Found the number of socket open exceeds $Cnt."
    kill -9 $PROCESS_ID
else
    echo "" #nothing to do.
fi

In crontab, I added this line but it seems not to kill the PID that I meant.

* * * * * sh /home/root/scripts/uwsgimonitor.sh

What am I missing?

Thank you in advance.

cn flag
This won't really solve your problem - you need to look at how to configure UWSGI/your webserver to limit the number of sockets opened, or allow the user it runs as to open more files via ulimits.conf.
deokyong song avatar
fr flag
I should've mentioned the background. I am an automation tester and this issue on the track fixed. Meanwhile, I just use this shell script to prevent any error message from popping up. It is just a temporary solution to test my app.
Score:0
fr flag

For those who want to how my situation went.

#!/bin/bash


count=$(lsof | awk '/uwsgi/ {print $1,$2}' | uniq -c | sort -r | head -1 | awk '{print $1}')
PROCESS_ID=$(lsof | awk '/uwsgi/ {print $1,$2}' | uniq -c | sort -r | head -1 | awk '{print $2}')
expectLimit=1000

echo "open socket:$count"
echo "pid:$PROCESS_ID"

if [[ ${count} -gt ${expectLimit} ]]
then
        echo "Found uwsgi exceeds limit :${expectLimit}"
        kill -9 $PROCESS_ID
else
        echo "" #nothing to do.
fi

This one works for me. Thanks.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.