Skip to content

Instantly share code, notes, and snippets.

@hkdsun
Created March 24, 2017 21:15
Show Gist options
  • Save hkdsun/54766f29b4603f066c8d31872cddbe9a to your computer and use it in GitHub Desktop.
Save hkdsun/54766f29b4603f066c8d31872cddbe9a to your computer and use it in GitHub Desktop.
#!/bin/bash
queue_file='/tmp/nbody.queue'
cmd="./test_cmd"
lock_file="/tmp/nbody.lock"
remove_first_in_queue() {
tail -n +2 "$queue_file" > "$queue_file.tmp" && mv "$queue_file.tmp" "$queue_file"
}
run_command() {
(
flock -n 9 || exit 1
eval "$cmd"
remove_first_in_queue
) 9>"$lock_file"
}
append_user_to_queue() {
user_is_in_queue=$(grep "$USER" "$queue_file")
if [ -z "$user_is_in_queue" ]; then
echo "$USER" >> $queue_file
fi
}
first_in_queue=$(head -1 "$queue_file")
if [ "$first_in_queue" == "$USER" ]; then
run_command
else
append_user_to_queue
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment