summaryrefslogtreecommitdiff
path: root/ghc/runtime/io/inputReady.lc
blob: fc8184e994d9c1a81b7e9d002b7490ae9551d162 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
%
% (c) The GRASP/AQUA Project, Glasgow University, 1994
%
\subsection[inputReady.lc]{hReady Runtime Support}

\begin{code}

#include "rtsdefs.h"
#include "stgio.h"

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

#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif

StgInt
inputReady(fp)
StgAddr fp;
{
    int flags;
    int c;

    if (feof((FILE *) fp))
	return 0;

    /* Get the original file status flags */
    while ((flags = fcntl(fileno((FILE *) fp), F_GETFL)) < 0) {
	/* highly unlikely */
	if (errno != EINTR) {
	    cvtErrno();
	    stdErrno();
	    return -1;
	}
    }

    /* If it's not already non-blocking, make it so */
    if (!(flags & O_NONBLOCK)) {
	while (fcntl(fileno((FILE *) fp), F_SETFL, flags | O_NONBLOCK) < 0) {
	    /* still highly unlikely */
	    if (errno != EINTR) {
		cvtErrno();
		stdErrno();
		return -1;
	    }
	}
    }
    /* Now try to get a character */
    while ((c = getc((FILE *) fp)) == EOF && errno == EINTR)
	clearerr((FILE *) fp);

    /* If we made it non-blocking for this, switch it back */
    if (!(flags & O_NONBLOCK)) {
	while (fcntl(fileno((FILE *) fp), F_SETFL, flags) < 0) {
	    /* still highly unlikely */
	    if (errno != EINTR) {
		cvtErrno();
		stdErrno();
		return -1;
	    }
	}
    }

    if (c == EOF) {
	if (errno == EAGAIN || feof((FILE *) fp)) {
	    clearerr((FILE *) fp);
	    return 0;
	} else {
	    cvtErrno();
	    stdErrno();
	    return -1;
	}
    } else if (ungetc(c, (FILE *) fp) == EOF) {
	cvtErrno();
	stdErrno();
	return -1;
    } else
	return 1;
}

\end{code}