summaryrefslogtreecommitdiffstats
path: root/src/io-unix.c
blob: d33312220076f5021ecef24d9d6c64ed518b8323 (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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/* io-unix.c - non-blocking io primitives for unix
 *
 * Copyright (C) 2009 Timo Teräs <timo.teras@iki.fi>
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 or later as
 * published by the Free Software Foundation.
 *
 * See http://www.gnu.org/ for details.
 */

int tf_open(struct tf_fd *fd, const char *pathname, int flags)
{
	int kfd, r;

	kfd = open(pathname, flags | O_CLOEXEC | O_NONBLOCK);
	if (unlikely(kfd < 0))
		return -errno;

	r = tf_fd_init(fd, kfd, TF_FD_AUTOCLOSE | TF_FD_STREAM_ORIENTED);
	if (r < 0) {
		close(kfd);
		return r;
	}
	return 0;
}

int tf_open_fd(struct tf_fd *fd, int kfd)
{
	int mode, flags = 0;

	mode = fcntl(kfd, F_GETFL, 0);
	if (!(mode & O_NONBLOCK)) {
		fcntl(fd->fd, F_SETFL, mode | O_NONBLOCK);
		flags |= TF_FD_RESTORE_BLOCKING;
	}

	return tf_fd_init(fd, kfd, TF_FD_STREAM_ORIENTED | flags);
}

int tf_close(struct tf_fd *fd)
{
	int r;

	if (fd->flags & TF_FD_RESTORE_BLOCKING) {
		fcntl(fd->fd, F_SETFL, fcntl(fd->fd, F_GETFL, 0) & ~O_NONBLOCK);
	}
	if (fd->flags & TF_FD_AUTOCLOSE) {
		r = close(fd->fd);
		if (unlikely(r == -1))
			return -errno;
	}
	return 0;
}

int tf_read(struct tf_fd *fd, void *buf, size_t count, tf_mtime_diff_t timeout)
{
	ssize_t n;
	int r, mode;

	mode = tf_schedule_timeout(timeout);
	tf_fd_wait(fd, EPOLLIN);
	do {
		n = read(fd->fd, buf, count);
		if (n == count) {
			r = 0;
			break;
		}
		if (n < 0) {
			if (errno == EINTR)
				continue;
			if (errno != EAGAIN) {
				r = errno;
				break;
			}
		} else if (n == 0) {
			r = EIO;
			break;
		} else {
			buf += n;
			count -= n;
			if (!(fd->flags & TF_FD_STREAM_ORIENTED))
				continue;
		}

		r = tf_schedule(mode);
		if (r != TF_WAKEUP_FD)
			break;
	} while (1);
	tf_fd_release(fd);

	return -r;
}

int tf_write(struct tf_fd *fd, const void *buf, size_t count,
	     tf_mtime_diff_t timeout)
{
	ssize_t n;
	int r, mode;

	mode = tf_schedule_timeout(timeout);
	tf_fd_wait(fd, EPOLLOUT);
	do {
		n = write(fd->fd, buf, count);
		if (n == count) {
			r = 0;
			break;
		}
		if (n < 0) {
			if (errno == EINTR)
				continue;
			if (errno != EAGAIN) {
				r = errno;
				break;
			}
		} else {
			buf += n;
			count -= n;
			if (!(fd->flags & TF_FD_STREAM_ORIENTED))
				continue;
		}

		r = tf_schedule(mode);
		if (r != TF_WAKEUP_FD)
			break;
	} while (1);
	tf_fd_release(fd);

	return -r;
}