2 % (c) The GRASP/AQUA Project, Glasgow University, 1994
4 \subsection[openFile.lc]{openFile Runtime Support}
11 #ifdef HAVE_SYS_TYPES_H
12 #include <sys/types.h>
15 #ifdef HAVE_SYS_STAT_H
40 * Since we aren't supposed to succeed when we're opening for writing and
41 * there's another writer, we can't just do an fopen() for "w" mode.
46 oflags = O_WRONLY | O_NOCTTY | O_APPEND;
50 oflags = O_WRONLY | O_NOCTTY;
54 oflags = how[1] == '+' ? O_RDWR | O_NOCTTY : O_RDONLY | O_NOCTTY;
58 fprintf(stderr, "openFile: unknown mode `%s'\n", how);
62 /* First try to open without creating */
63 while ((fd = open(file, oflags, 0666)) < 0) {
64 if (errno == ENOENT) {
65 if (how[0] == 'r' && how[1] == '\0') {
66 /* For ReadMode, just bail out now */
67 ghc_errtype = ERR_NOSUCHTHING;
68 ghc_errstr = "file does not exist";
71 /* Now try to create it */
72 while ((fd = open(file, oflags | O_CREAT | O_EXCL, 0666)) < 0) {
73 if (errno == EEXIST) {
74 /* Race detected; go back and open without creating it */
76 } else if (errno != EINTR) {
84 ghc_errtype = ERR_NOSUCHTHING;
85 ghc_errstr = "no path to file";
88 ghc_errtype = ERR_PERMISSIONDENIED;
89 ghc_errstr = "unsupported owner or group";
99 } else if (errno != EINTR) {
106 ghc_errtype = ERR_NOSUCHTHING;
107 ghc_errstr = "no path to file";
110 ghc_errtype = ERR_PERMISSIONDENIED;
111 ghc_errstr = "unsupported owner or group";
118 /* Make sure that we aren't looking at a directory */
120 while (fstat(fd, &sb) < 0) {
121 /* highly unlikely */
122 if (errno != EINTR) {
130 if (S_ISDIR(sb.st_mode)) {
131 ghc_errtype = ERR_INAPPROPRIATETYPE;
132 ghc_errstr = "file is a directory";
133 /* We can't have created it in this case. */
138 /* Use our own personal locking */
140 if (lockFile(fd, exclusive) < 0) {
148 ghc_errtype = ERR_RESOURCEBUSY;
149 ghc_errstr = "file is locked";
159 * Write mode is supposed to truncate the file. Unfortunately, our pal
160 * ftruncate() is non-POSIX, so we truncate with a second open, which may fail.
167 while ((fd2 = open(file, oflags, 0666)) < 0) {
168 if (errno != EINTR) {
178 ghc_errtype = ERR_RESOURCEBUSY;
179 ghc_errstr = "enforced lock prevents truncation";
182 ghc_errtype = ERR_NOSUCHTHING;
183 ghc_errstr = "no path to file";
186 ghc_errtype = ERR_PERMISSIONDENIED;
187 ghc_errstr = "unsupported owner or group";
195 errno = 0; /* Just in case fdopen() is lame */
196 while ((fp = fdopen(fd, how)) == NULL) {
197 if (errno != EINTR) {