2 * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
4 * $Id: getLock.c,v 1.5 1999/03/01 09:11:39 sof Exp $
6 * stdin/stout/stderr Runtime Support
12 #ifdef HAVE_SYS_TYPES_H
13 #include <sys/types.h>
16 #ifdef HAVE_SYS_STAT_H
29 #define FD_SETSIZE 256
38 static Lock readLock[FD_SETSIZE];
39 static Lock writeLock[FD_SETSIZE];
41 static int readLocks = 0;
42 static int writeLocks = 0;
45 lockFile(fd, for_writing, exclusive)
53 while (fstat(fd, &sb) < 0) {
59 /* Only lock regular files */
60 if (!S_ISREG(sb.st_mode))
64 /* opening a file for writing, check to see whether
65 we don't have any read locks on it already.. */
66 for (i = 0; i < readLocks; i++) {
67 if (readLock[i].inode == sb.st_ino && readLock[i].device == sb.st_dev) {
76 /* If we're determined that there is only a single
77 writer to the file, check to see whether the file
78 hasn't already been opened for writing..
81 for (i = 0; i < writeLocks; i++) {
82 if (writeLock[i].inode == sb.st_ino && writeLock[i].device == sb.st_dev) {
92 /* OK, everything is cool lock-wise, record it and leave. */
94 writeLock[i].device = sb.st_dev;
95 writeLock[i].inode = sb.st_ino;
99 /* For reading, it's simpler - just check to see
100 that there's no-one writing to the underlying file. */
101 for (i = 0; i < writeLocks; i++) {
102 if (writeLock[i].inode == sb.st_ino && writeLock[i].device == sb.st_dev) {
111 /* Fit in new entry, reusing an existing table entry, if possible. */
112 for (i = 0; i < readLocks; i++) {
113 if (readLock[i].inode == sb.st_ino && readLock[i].device == sb.st_dev) {
118 readLock[i].device = sb.st_dev;
119 readLock[i].inode = sb.st_ino;
132 for (i = 0; i < readLocks; i++)
133 if (readLock[i].fd == fd) {
134 while (++i < readLocks)
135 readLock[i - 1] = readLock[i];
140 for (i = 0; i < writeLocks; i++)
141 if (writeLock[i].fd == fd) {
142 while (++i < writeLocks)
143 writeLock[i - 1] = writeLock[i];
147 /* Signal that we did not find an entry */
151 /* getLock() is used when opening the standard file descriptors */
153 getLock(fd, for_writing)
157 if (lockFile(fd, for_writing, 0) < 0) {
168 ghc_errtype = ERR_RESOURCEBUSY;
169 ghc_errstr = "file is locked";
172 /* Not so sure we want to do this, since getLock()
173 is only called on the standard file descriptors.. */
174 /*(void) close(fd); */