Skip to content

Instantly share code, notes, and snippets.

@arkku
Last active July 9, 2019 18:02
Show Gist options
  • Save arkku/df879fa93341b11106925d98791d67b2 to your computer and use it in GitHub Desktop.
Save arkku/df879fa93341b11106925d98791d67b2 to your computer and use it in GitHub Desktop.
mosh + tmux helper to kill disconnected leftover sessions from the same machine
#!/bin/sh
host="$1"
[ -z "$host" ] && host=homeshell
port="$2"
[ -z "$port" ] && port=60001
slave="$3"
[ -z "$slave" ] && slave=`hostname -s` # use a fixed string if needed
main=$4
[ -z "$main" ] && main=0
session="${main}_${slave}"
server="env MOSH_SERVER_SIGNAL_TMOUT=20 mosh-server"
attempted_detach=0
while true; do
if mosh --server="$server" -P "$port" "$host" -- bin/tmx prefix '^b' "$main" "$slave"; then
exit 0
elif [ $attempted_detach = 1 ]; then
exit 1
fi
# Try to detach the existing client from holding up our port
# (it will not detach if it is still live due to -P and
# MOSH_SERVER_SIGNAL_TMOUT)
echo "Attempting to detach session $session..." >&2
ssh "$host" -- tmux lsc -F '\#{client_pid}' -t "$session" \| \
xargs ps -o ppid= \| xargs kill -SIGUSR1 >&2
attempted_detach=1
done
@arkku
Copy link
Author

arkku commented Jul 9, 2019

(And yes, of course you could just unconditionally send SIGUSR1 to every mosh-server to kill all the idle ones, but that's not wanted here, since they may be legitimate sessions from other devices that are sleeping at the moment. And at the same time, I want to keep the idle threshold very short, i.e., shorter than the time it takes to reboot.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment