2 * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
4 * $Id: getLock.c,v 1.4 1999/02/04 12:13:15 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) {
72 /* If we're determined that there is only a single
73 writer to the file, check to see whether the file
74 hasn't already been opened for writing..
77 for (i = 0; i < writeLocks; i++) {
78 if (writeLock[i].inode == sb.st_ino && writeLock[i].device == sb.st_dev) {
84 /* OK, everything is cool lock-wise, record it and leave. */
86 writeLock[i].device = sb.st_dev;
87 writeLock[i].inode = sb.st_ino;
91 /* For reading, it's simpler - just check to see
92 that there's no-one writing to the underlying file. */
93 for (i = 0; i < writeLocks; i++) {
94 if (writeLock[i].inode == sb.st_ino && writeLock[i].device == sb.st_dev) {
99 /* Fit in new entry, reusing an existing table entry, if possible. */
100 for (i = 0; i < readLocks; i++) {
101 if (readLock[i].inode == sb.st_ino && readLock[i].device == sb.st_dev) {
106 readLock[i].device = sb.st_dev;
107 readLock[i].inode = sb.st_ino;
120 for (i = 0; i < readLocks; i++)
121 if (readLock[i].fd == fd) {
122 while (++i < readLocks)
123 readLock[i - 1] = readLock[i];
128 for (i = 0; i < writeLocks; i++)
129 if (writeLock[i].fd == fd) {
130 while (++i < writeLocks)
131 writeLock[i - 1] = writeLock[i];
135 /* Signal that we did not find an entry */
139 /* getLock() is used when opening the standard file descriptors */
141 getLock(fd, for_writing)
145 if (lockFile(fd, for_writing, 0) < 0) {
156 ghc_errtype = ERR_RESOURCEBUSY;
157 ghc_errstr = "file is locked";
160 /* Not so sure we want to do this, since getLock()
161 is only called on the standard file descriptors.. */
162 /*(void) close(fd); */