Issue
I have a script:
#!/bin/bash
gb=1
ps aux | awk '{print $2 "\t\t" $6/1024 " MB\t\t" $11}' | while IFS=\n read PROCESS; do
MEMORY=$( echo $PROCESS | awk '{print $2}' | cut -d'.' -f 1 )
if [[ $MEMORY -gt $gb ]]
then
echo $PROCESS | grep apache
pid=$(echo $PROCESS | grep apache | awk '{print $1}')
kill $pid > /dev/null 2>&1
fi
done
it removes apache processes that are greater than the value specified in the "gb" variable
I need the script to log: the end date of the process, its pid and the username to which the process belonged.
How can the script be modified?
Solution
Since I'm not interested in nuking processes on my own machine, that part is not tested, but something like this might be a good start:
#!/bin/sh
gb=1
ps aux | grep [a]pache | awk -vgb=$gb '
BEGIN {
printf("%-16s %8s END-DATE\n", "USER", "PID");
}
{
if ($6 < gb * 1024 * 1024)
next;
system("kill " $2)
# Give the process 10s to terminate
for (i = 0; i < 10; i++) {
if (system("kill -0 "$2)) {
printf("%-16s %8u %s\n", $1, $2, strftime());
next;
}
system("sleep 1");
}
printf("%-16s %8u DID-NOT-TERMINATE\n", $1, $2);
}'
Answered By - wkz Answer Checked By - David Marino (WPSolving Volunteer)