How to kill all the processes that have dates older than today?
I issue the command ps -aux | grep tony
. It displays the following output
tony 10986 0.0 0.0 33532 464 ? S Feb01 0:00 vncconfig -iconic
tony 10988 0.0 0.0 86012 512 ? S Feb01 0:00 twm
tony 15553 0.0 0.0 92404 1848 ? S 10:34 0:00 sshd: tony@pts/34
tony 15554 0.0 0.0 66232 1680 pts/34 Ss+ 10:34 0:00 -bash
I would like kill all the my dead processes that have dates older than today.
I could have issued the command kill -9 10986
; kill -9 10988
, but I like to execute in one command and also there are many dead processes pending.
Any help would be much appreciated.
First, pay attention to Jonathan's advice
Now that you've done that, try something like this
# Find all process that are owner by "tony"
# - Print out the process id (pid), and the start time (lstart)
# Find all the rows that aren't for today
# Cut that down to just the first field (process id)
PROCS="$(ps -u tony -o pid,lstart | fgrep -v " $( date '+%a %b %d' )" | cut -d' ' -f1)"
# Run through each process and ask it to shutdown
for PROC in $PROCS
do
kill -TERM $PROC
done
# Wait for 10 seconds to give the processes time to stop
sleep 10
# Kill off any processes that still exist
for PROC in $PROCS
do
[ -r /proc/${PROC}/status ] && kill -KILL $PROC
done
Though you may not actually want to do this.
All processes are attached to sessions, if you can work out what your old VNC session was, then you should be able to kill the processes that belong to that session, rather than just looking for "old" processes.
- Be very careful not to kill daemon processes for the system.
- Why do you need to kill Tony's processes that are older than a day old?
- Sending SIGKILL (-9) is brutal. It is better to send SIGTERM (15) and SIGHUP (1) before sending SIGKILL. The SIGHUP and SIGTERM signals give the process a chance to clean up and exit under control; simply sending SIGKILL means that lock files cannot be cleaned up, for example.
To obtain a list of your processes started long enough ago that the process has a date instead of a time in the time field, you could use:
pids=$(ps -aux |
awk '$1 ~ /^tony$/ && $9 !~ /[0-2]?[0-9]:[0-5][0-9]/ { print $2; }')
for signal in 15 1 9
do
kill -$signal $pids 2>/dev/null
sleep 1
done
The awk
script looks for lines that start with 'tony' but don't match a time in column 9 - they have a date and are, therefore 'old'. As suggested, the signalling is done in 3 steps: terminate, hangup, kill. With care, you can pass the username to the awk
script instead of hardwiring the name as tony
.