Last active
August 29, 2015 14:15
-
-
Save v6ak/51cf5c929e199c13715c to your computer and use it in GitHub Desktop.
Starts a GUI application if not running. If it is running, it switches to it. It is unlikely to work well with multiwindow applications without modification because it focuses all of application's windows. Does not work well with "minimize to tray", because it can't find the app's window.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -u | |
set -e | |
set -o pipefail | |
# Settings | |
NAME=GQueues | |
COMMAND=firefox-gqueues | |
PREFIX="$HOME/.cache/$NAME-$(id -u)" | |
LOCKFILE="$PREFIX.lock" | |
PIDFILE="$PREFIX.pid" | |
subpids () { | |
echo $1 | |
for i in $( ps --no-headers --ppid $1 -o pid); do | |
subpids $i | |
done | |
} | |
umask 007 | |
if | |
( # TODO: Add trap(s) for kill&cleanup | |
flock -n 9 || exit 5 | |
echo critical section: enter | |
$COMMAND & | |
child_pid=$! | |
echo PID: $child_pid | |
echo -n $child_pid > "$PIDFILE" | |
echo -n "Waiting…" | |
wait "$child_pid" | |
echo DONE | |
rm "$PIDFILE" "$LOCKFILE" | |
echo critical section: exit | |
) 9> "$LOCKFILE"; | |
RET=$?; | |
[ "$RET" != 0 ] | |
then | |
if [ "$RET" == 5 ]; then | |
echo "Can't lock" | |
focused=0 | |
main_pid=$(cat "$PIDFILE") | |
for pid in $(subpids "$main_pid"); do | |
for winid in $(xdotool search --pid "$pid"); do | |
echo "winid: $winid" | |
xdotool windowraise "$winid" | |
xdotool windowfocus "$winid" || true | |
echo "focused: $focused" | |
focused=1 | |
done | |
done | |
if [ "$focused" != 1 ]; then | |
notify-send "Can't focus $NAME!" | |
exit 2 | |
fi | |
else | |
echo unknown error: $RET | |
exit 1 | |
fi | |
else | |
echo 0 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$PREFIX should NOT be in tmpdir, since it would be vulnerable to symlink race condition: https://en.wikipedia.org/wiki/Symlink_race