2 * (c) The GRASP/AQUA Project, Glasgow University, 1994-2004
4 * $Id: lockFile.c,v 1.3 2004/06/02 12:35:11 simonmar Exp $
6 * stdin/stout/stderr Runtime Support
11 #include "../../ghc/rts/RtsUtils.h" // for barf()
13 #ifdef mingw32_TARGET_OS
14 // The Win32 C runtime has a max of 2048 file descriptors (see
15 // _NHANDLE_ in the crt sources), but mingw defines FD_SETSIZE to
20 # error No FD_SETSIZE defined!
22 # define NUM_FDS FD_SETSIZE
32 static Lock readLock[NUM_FDS];
33 static Lock writeLock[NUM_FDS];
35 static int readLocks = 0;
36 static int writeLocks = 0;
39 lockFile(int fd, int for_writing, int exclusive)
45 barf("lockFile: fd out of range");
48 while (fstat(fd, &sb) < 0) {
53 /* fstat()ing socket fd's seems to fail with CRT's fstat(),
54 so let's just silently return and hope for the best..
62 /* opening a file for writing, check to see whether
63 we don't have any read locks on it already.. */
64 for (i = 0; i < readLocks; i++) {
65 if (readLock[i].inode == sb.st_ino && readLock[i].device == sb.st_dev) {
73 /* If we're determined that there is only a single
74 writer to the file, check to see whether the file
75 hasn't already been opened for writing..
78 for (i = 0; i < writeLocks; i++) {
79 if (writeLock[i].inode == sb.st_ino && writeLock[i].device == sb.st_dev) {
88 /* OK, everything is cool lock-wise, record it and leave. */
90 writeLock[i].device = sb.st_dev;
91 writeLock[i].inode = sb.st_ino;
95 /* For reading, it's simpler - just check to see
96 that there's no-one writing to the underlying file. */
97 for (i = 0; i < writeLocks; i++) {
98 if (writeLock[i].inode == sb.st_ino && writeLock[i].device == sb.st_dev) {
106 /* Fit in new entry, reusing an existing table entry, if possible. */
107 for (i = 0; i < readLocks; i++) {
108 if (readLock[i].inode == sb.st_ino && readLock[i].device == sb.st_dev) {
113 readLock[i].device = sb.st_dev;
114 readLock[i].inode = sb.st_ino;
126 for (i = 0; i < readLocks; i++)
127 if (readLock[i].fd == fd) {
128 while (++i < readLocks)
129 readLock[i - 1] = readLock[i];
134 for (i = 0; i < writeLocks; i++)
135 if (writeLock[i].fd == fd) {
136 while (++i < writeLocks)
137 writeLock[i - 1] = writeLock[i];
141 /* Signal that we did not find an entry */