summaryrefslogtreecommitdiff
path: root/ghc/lib/std/cbits/getBufferMode.c
blob: 8ce42f9f4222e9605bb7fde9942d029ec3163d0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* 
 * (c) The GRASP/AQUA Project, Glasgow University, 1994-1998
 *
 * $Id: getBufferMode.c,v 1.5 2001/04/02 16:10:32 rrt Exp $
 *
 * hIs...Buffered Runtime Support
 */

#include "Rts.h"
#include "stgio.h"

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif

/*
 * We try to guess what the default buffer mode is going to be based 
 * on the type of file we're attached to.
 */

#define GBM_NB (0)
#define GBM_LB (-1)
#define GBM_BB (-2)
#define GBM_ERR (-3)

StgInt
getBufferMode(ptr)
StgForeignPtr ptr;
{
    IOFileObject* fo = (IOFileObject*)ptr;
    struct stat sb;
    int fd = fo->fd;

    /* Try to find out the file type */
    while (fstat(fd, &sb) < 0) {
	/* highly unlikely */
	if (errno != EINTR) {
	    cvtErrno();
	    stdErrno();
	    return GBM_ERR;
	}
    }
    /* Terminals are line-buffered by default */
    if (S_ISCHR(sb.st_mode) && isatty(fd) == 1) {
        fo ->flags |= FILEOBJ_LB;
	return GBM_LB;
    /* Default size block buffering for the others */
    } else {
        fo ->flags |= FILEOBJ_BB;
	return GBM_BB;
    }
}