1 /* COPYING ******************************************************************
2 For copyright and licensing terms, see the file named COPYING.
3 // **************************************************************************
4 */
5
6 #include <sys/types.h>
7 #include <sys/file.h>
8 #include <unistd.h>
9 #include "lockfile.h"
10 #include "FileDescriptorOwner.h"
11
12 extern
13 int
open_lockfile_exclusive_or_wait_at(int dir_fd,const char * name)14 open_lockfile_exclusive_or_wait_at (
15 int dir_fd,
16 const char * name
17 ) {
18 #if defined O_EXLOCK
19 return openat(dir_fd, name, O_NOCTTY|O_CLOEXEC|O_WRONLY|O_CREAT|O_APPEND|O_EXLOCK, 0600);
20 #else
21 FileDescriptorOwner lock_fd(openat(dir_fd, name, O_NOCTTY|O_CLOEXEC|O_WRONLY|O_CREAT|O_APPEND, 0600));
22 if (0 <= lock_fd.get()) {
23 if (0 > flock(lock_fd.get(), LOCK_EX))
24 return -1;
25 }
26 return lock_fd.release();
27 #endif
28 }
29
30 extern
31 int
open_lockfile_shared_or_wait_at(int dir_fd,const char * name)32 open_lockfile_shared_or_wait_at (
33 int dir_fd,
34 const char * name
35 ) {
36 #if defined O_EXLOCK
37 return openat(dir_fd, name, O_NOCTTY|O_CLOEXEC|O_WRONLY|O_CREAT|O_APPEND|O_SHLOCK, 0600);
38 #else
39 FileDescriptorOwner lock_fd(openat(dir_fd, name, O_NOCTTY|O_CLOEXEC|O_WRONLY|O_CREAT|O_APPEND, 0600));
40 if (0 <= lock_fd.get()) {
41 if (0 > flock(lock_fd.get(), LOCK_SH))
42 return -1;
43 }
44 return lock_fd.release();
45 #endif
46 }
47