summaryrefslogtreecommitdiff
path: root/scripts/vyatta-monitor-cleanup
blob: 553c1f8790f9505a05de6f0c9262554151393f7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/bin/bash
declare CURRENT_PTS=$(tty | sed -e s-/--g -e s/dev//g)
declare CURRENT_UID=$(id -u)
declare CURRENT_UNAME=$(id -un)
declare -a MPIDS
MODE=$1
MPIDS=( $(ls /var/run/vyatta/monitor/*.pid 2> /dev/null ) )

for pidfile in "${MPIDS[@]}"; do
  pid=$(<$pidfile)
  procname=$(cat /proc/$pid/cmdline 2>/dev/null)
  if [[ "$procname" =~ "tail" ]] ; then
    # Clean up tail processes that didn't die on logout
    pts=${pidfile##*-pts}
    pts=${pts%%.pid}
    # If the process isn't attaced to the current PTY
    if [[ "pts$pts" != "$CURRENT_PTS" ]]; then
      # If I owned this process
      if cat /proc/$pid/status | grep -q "Uid:.*$CURRENT_UID" ; then 
        # If I'm no longer on the pty that process started on
        if ! who  | grep -q "$CURRENT_UNAME.*pts/$pts" ; then 
          kill $pid
          rm -rf $pidfile
        fi
      fi
    elif [[ "$MODE" == "LOGOUT" ]]; then
      # on logout kill all monitors
      kill $pid
      rm -rf $pidfile
    fi
  else 
    # Clean up killed tail processes
    rm -rf $pidfile
  fi
done