util-lockfile.c (2147B)
1 // $Id$ --*- c -*-- 2 3 // Copyright (C) 2004 Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de> 4 // 5 // This program is free software; you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation; version 2 of the License. 8 // 9 // This program is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with this program; if not, write to the Free Software 16 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 17 18 19 #ifdef HAVE_CONFIG_H 20 # include <config.h> 21 #endif 22 23 #include "util-lockfile.h" 24 #include "errinfo.h" 25 26 #include <signal.h> 27 #include <stdlib.h> 28 #include <unistd.h> 29 #include <fcntl.h> 30 #include <sys/file.h> 31 #include <errno.h> 32 33 static volatile sig_atomic_t alarm_flag = 0; 34 35 static void 36 alarmFunc(int UNUSED sig) 37 { 38 alarm_flag = 1; 39 signal(SIGALRM, alarmFunc); 40 } 41 42 bool 43 lockfile(int *fd, char const *filename, int op, long timeout, 44 struct ErrorInformation *err) 45 { 46 char const *errstr = 0; 47 void (*old_sighandler)(int) = 0; 48 49 errstr = "open()"; 50 *fd = open(filename, O_CREAT|O_RDONLY|O_NOFOLLOW|O_NONBLOCK, 0644); 51 if (*fd==-1) goto err; 52 53 if (timeout!=-1) { 54 errstr = "siginterrupt()"; 55 if (siginterrupt(SIGALRM, 1)==-1) goto err; 56 57 errstr = "signal()"; 58 old_sighandler = signal(SIGALRM, alarmFunc); 59 if (old_sighandler==SIG_ERR) goto err; 60 61 alarm(timeout); 62 } 63 64 errstr = "lockf()"; 65 while (lockf(*fd, op, 0)==-1) { 66 if ((errno!=EINTR && errno!=EINTR) || alarm_flag) goto err; 67 } 68 69 if (timeout!=-1 && old_sighandler!=0) 70 signal(SIGALRM, old_sighandler); 71 72 errstr = "fcntl()"; 73 if (fcntl(*fd, F_SETFD, FD_CLOEXEC)==-1) goto err; 74 75 return true; 76 77 err: 78 if (err) { 79 err->pos = errstr; 80 err->id = errno; 81 } 82 if (timeout!=-1 && old_sighandler!=0) 83 signal(SIGALRM, old_sighandler); 84 if (*fd!=-1) close(*fd); 85 return false; 86 }