721246b126699532c8a213a6a8e8d1439f3fc991
2 * (c) The GRASP/AQUA Project, Glasgow University, 1994-2004
4 * $Id: lockFile.c,v 1.5 2005/01/28 13:36:32 simonmar Exp $
6 * stdin/stout/stderr Runtime Support
9 #if !(defined(_MSC_VER) || defined(__MINGW32__) || defined(_WIN32))
21 static Lock readLock
[FD_SETSIZE
];
22 static Lock writeLock
[FD_SETSIZE
];
24 static int readLocks
= 0;
25 static int writeLocks
= 0;
28 lockFile(int fd
, int for_writing
, int exclusive
)
33 if (fd
> FD_SETSIZE
) {
34 barf("lockFile: fd out of range");
37 while (fstat(fd
, &sb
) < 0) {
43 /* opening a file for writing, check to see whether
44 we don't have any read locks on it already.. */
45 for (i
= 0; i
< readLocks
; i
++) {
46 if (readLock
[i
].inode
== sb
.st_ino
&& readLock
[i
].device
== sb
.st_dev
)
49 /* If we're determined that there is only a single
50 writer to the file, check to see whether the file
51 hasn't already been opened for writing..
54 for (i
= 0; i
< writeLocks
; i
++) {
55 if (writeLock
[i
].inode
== sb
.st_ino
&& writeLock
[i
].device
== sb
.st_dev
) {
60 /* OK, everything is cool lock-wise, record it and leave. */
62 writeLock
[i
].device
= sb
.st_dev
;
63 writeLock
[i
].inode
= sb
.st_ino
;
67 /* For reading, it's simpler - just check to see
68 that there's no-one writing to the underlying file. */
69 for (i
= 0; i
< writeLocks
; i
++) {
70 if (writeLock
[i
].inode
== sb
.st_ino
&& writeLock
[i
].device
== sb
.st_dev
)
73 /* Fit in new entry, reusing an existing table entry, if possible. */
74 for (i
= 0; i
< readLocks
; i
++) {
75 if (readLock
[i
].inode
== sb
.st_ino
&& readLock
[i
].device
== sb
.st_dev
) {
80 readLock
[i
].device
= sb
.st_dev
;
81 readLock
[i
].inode
= sb
.st_ino
;
93 for (i
= 0; i
< readLocks
; i
++)
94 if (readLock
[i
].fd
== fd
) {
95 while (++i
< readLocks
)
96 readLock
[i
- 1] = readLock
[i
];
101 for (i
= 0; i
< writeLocks
; i
++)
102 if (writeLock
[i
].fd
== fd
) {
103 while (++i
< writeLocks
)
104 writeLock
[i
- 1] = writeLock
[i
];
108 /* Signal that we did not find an entry */