2 * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
4 * $Id: openFile.c,v 1.1 1998/04/10 10:54:42 simonm Exp $
6 * openFile Runtime Support
12 #ifdef HAVE_SYS_TYPES_H
13 #include <sys/types.h>
16 #ifdef HAVE_SYS_STAT_H
29 openFile(StgByteArray file, StgByteArray how)
39 * Since we aren't supposed to succeed when we're opening for writing and
40 * there's another writer, we can't just do an fopen() for "w" mode.
45 oflags = O_WRONLY | O_NOCTTY | O_APPEND;
49 oflags = O_WRONLY | O_NOCTTY;
53 oflags = how[1] == '+' ? O_RDWR | O_NOCTTY : O_RDONLY | O_NOCTTY;
57 fprintf(stderr, "openFile: unknown mode `%s'\n", how);
61 /* First try to open without creating */
62 while ((fd = open(file, oflags, 0666)) < 0) {
63 if (errno == ENOENT) {
64 if (how[0] == 'r' && how[1] == '\0') {
65 /* For ReadMode, just bail out now */
66 ghc_errtype = ERR_NOSUCHTHING;
67 ghc_errstr = "file does not exist";
70 /* If it is a dangling symlink, break off now, too. */
72 if ( lstat(file,&st) == 0) {
73 ghc_errtype = ERR_NOSUCHTHING;
74 ghc_errstr = "dangling symlink";
78 /* Now try to create it */
79 while ((fd = open(file, oflags | O_CREAT | O_EXCL, 0666)) < 0) {
80 if (errno == EEXIST) {
81 /* Race detected; go back and open without creating it */
83 } else if (errno != EINTR) {
91 ghc_errtype = ERR_NOSUCHTHING;
92 ghc_errstr = "no path to file";
95 ghc_errtype = ERR_PERMISSIONDENIED;
96 ghc_errstr = "unsupported owner or group";
106 } else if (errno != EINTR) {
113 ghc_errtype = ERR_NOSUCHTHING;
114 ghc_errstr = "no path to file";
117 ghc_errtype = ERR_PERMISSIONDENIED;
118 ghc_errstr = "unsupported owner or group";
125 /* Make sure that we aren't looking at a directory */
127 while (fstat(fd, &sb) < 0) {
128 /* highly unlikely */
129 if (errno != EINTR) {
137 if (S_ISDIR(sb.st_mode)) {
138 ghc_errtype = ERR_INAPPROPRIATETYPE;
139 ghc_errstr = "file is a directory";
140 /* We can't have created it in this case. */
145 /* Use our own personal locking */
147 if (lockFile(fd, exclusive) < 0) {
155 ghc_errtype = ERR_RESOURCEBUSY;
156 ghc_errstr = "file is locked";
166 * Write mode is supposed to truncate the file. Unfortunately, our pal
167 * ftruncate() is non-POSIX, so we truncate with a second open, which may fail.
174 while ((fd2 = open(file, oflags, 0666)) < 0) {
175 if (errno != EINTR) {
185 ghc_errtype = ERR_RESOURCEBUSY;
186 ghc_errstr = "enforced lock prevents truncation";
189 ghc_errtype = ERR_NOSUCHTHING;
190 ghc_errstr = "no path to file";
193 ghc_errtype = ERR_PERMISSIONDENIED;
194 ghc_errstr = "unsupported owner or group";
202 errno = 0; /* Just in case fdopen() is lame */
203 while ((fp = fdopen(fd, how)) == NULL) {
204 if (errno != EINTR) {