[project @ 1998-11-26 09:17:22 by sof]
[ghc-hetmet.git] / ghc / lib / std / cbits / closeFile.lc
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1994
3 %
4 \subsection[closeFile.lc]{hClose Runtime Support}
5
6 \begin{code}
7
8 #include "rtsdefs.h"
9 #include "stgio.h"
10
11 StgInt __really_close_stdfiles=1;
12
13 StgInt
14 closeFile(ptr,flush_buf)
15 StgForeignObj ptr;
16 StgInt flush_buf;
17 {
18     IOFileObject* fo = (IOFileObject*)ptr;
19     int rc = 0;
20     int unlocked=1;
21
22     /* Already closed, shouldn't occur. */
23     if ( fo == NULL ) {
24        return 0;
25     }
26
27     if ( flush_buf != 0 && (fo->flags & FILEOBJ_FLUSH) ) {
28        writeFileObject(ptr,fo->bufWPtr);
29     }
30
31     /* If the flush failed, we ignore this and soldier on.. */
32
33     if ( unlockFile(fo->fd) ) {
34       /* If the file has already been unlocked (or an entry
35          for it in the locking tables couldn't be found), could
36          mean two things:
37
38             - we're repeating an hClose on an already
39               closed file (this is likely to be a bug
40               in the implementation of hClose, as this 
41               condition should have been caught before
42               we ended up here.)
43               
44             - the file wasn't locked in the first place!
45               (file descriptors to non regular files.)
46
47          We proceed with attempting to close the file,
48          but don't flag the error should close() return
49          EBADF
50       */
51         unlocked=0;
52         
53     }
54
55     /* Closing file descriptors that refer to standard channels
56        is problematic, so we back off from doing this by default,
57        just closing them at the Handle level. If you insist on
58        closing them, setting the (global) variable 
59        __really_close_stdfiles to 0 turns off this behaviour.
60     */
61     if ( (fo->flags & FILEOBJ_STD) && __really_close_stdfiles ) {
62         ;
63
64     } else  {
65       /* Regardless of success or otherwise, the fd field gets smashed. */
66       while ( (rc = close(fo->fd)) != 0 ) {
67          /* See above unlockFile() comment */
68          if ( errno != EINTR && (!unlocked && errno != EBADF ) ) {
69             cvtErrno();
70             stdErrno();
71             fo->fd = -1;
72             return rc;
73         }
74       }
75     }
76     fo->fd = -1;
77     return 0;
78 }
79
80 \end{code}