[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / lib / std / cbits / freeFile.c
1 /* 
2  * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
3  *
4  * $Id: freeFile.c,v 1.3 1998/12/02 13:27:34 simonm Exp $
5  *
6  * Giving up files
7  */
8
9 #include "Rts.h"
10 #include "stgio.h"
11 #include "fileObject.h"
12
13 /* sigh, the FILEs attached to the standard descriptors are 
14    handled differently. We don't want them freed via the
15    ForeignObj finaliser, as we probably want to use these
16    before we *really* shut down (dumping stats etc.)
17 */
18 void freeStdFile(fp)
19 StgForeignPtr fp;
20 { return; }
21
22 void freeStdFileObject(ptr)
23 StgForeignPtr ptr;
24
25   IOFileObject* fo = (IOFileObject*)ptr;
26
27   /* Don't close the file, just flush the buffer */
28   if (fo != NULL && fo->fd != -1) {
29     if (fo->buf != NULL && (fo->flags & FILEOBJ_FLUSH) && fo->bufWPtr > 0) {
30        /* Flush buffer contents */
31        writeBuffer((StgForeignPtr)fo, fo->bufWPtr);
32     }
33   }
34 }
35
36 void freeFileObject(ptr)
37 StgForeignPtr ptr;
38 {
39     /*
40      * The finaliser for the file objects embedded in Handles. The RTS
41      * assumes that the finaliser runs without problems, so all
42      * we can do here is flish buffers + close(), and hope nothing went wrong.
43      *
44      */
45
46     int rc;
47     IOFileObject* fo = (IOFileObject*)ptr;
48
49     if ( fo == NULL )
50       return;
51
52     if ( fo->fd == -1 || (rc = unlockFile(fo->fd)) ) {
53         /* If the file handle has been explicitly closed
54          * (via closeFile()), we will have given
55          * up our process lock, so we break off and just return.
56          */
57        return;
58     }
59
60     if (fo->buf != NULL && fo->bufWPtr > 0) {
61        /* Flush buffer contents before closing underlying file */
62        fo->flags &= ~FILEOBJ_RW_WRITE | ~FILEOBJ_RW_READ;
63        flushFile(ptr);
64     }
65
66     rc = close(fo->fd);
67     /* Error or no error, we don't care.. */
68
69     return;
70 }
71
72 StgAddr ref_freeStdFileObject(void)
73 {
74     return (StgAddr)&freeStdFileObject;
75 }
76
77 StgAddr ref_freeFileObject(void)
78 {
79     return (StgAddr)&freeFileObject;
80 }
81