Added ionice when available.
[scripts.git] / withlock.sh
1 #!/bin/bash
2
3 #########################################################################
4 # This program is free software: you can redistribute it and/or modify  #
5 # it under the terms of the version 3 of the GNU General Public License #
6 # as published by the Free Software Foundation.                         #
7 #                                                                       #
8 # This program is distributed in the hope that it will be useful, but   #
9 # WITHOUT ANY WARRANTY; without even the implied warranty of            #
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      #
11 # General Public License for more details.                              #
12 #                                                                       #
13 # You should have received a copy of the GNU General Public License     #
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.  #
15 #                                                                       #
16 # Written by and Copyright (C) Francois Fleuret                         #
17 # Contact <francois.fleuret@idiap.ch> for comments & bug reports        #
18 #########################################################################
19
20 # This command allows to call another command with a lockfile to avoid
21 # concurrent executions for the same user.
22
23 set -e
24
25 if [[ ! $1 ]]; then
26     echo "withlock.sh <command> [command args]"
27     exit 1
28 fi
29
30 LOCKFILE=/tmp/lock$(which $1 | sed -e "s:/:-:g").${USER}
31
32 (set -C && : > ${LOCKFILE}) 2> /dev/null
33
34 if [ $? != "0" ]; then
35     echo "Lockfile ${LOCKFILE} exists." >&2
36     exit 1
37 fi
38
39 trap 'rm ${LOCKFILE}' EXIT
40
41 $*