summaryrefslogtreecommitdiff
path: root/ioexact.c
blob: 1600784d993eb8871d27d47e65d2df0cce786ac2 (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
#include <errno.h>
#include <unistd.h>
#include <signal.h>

#include "ioexact.h"

extern volatile sig_atomic_t sigint;

ssize_t read_exact(int fd, void *buf, size_t len, int mayexit)
{
	ssize_t num = 0, written;

	while (len > 0 && !sigint) {
		if ((written = read(fd, buf, len)) < 0) {
			if (errno == EAGAIN && num > 0)
				continue;
			if (mayexit)
				return -1;
			else
				continue;
		}
		if (!written)
			return 0;
		len -= written;
		buf += written;
		num += written;
	}

	return num;
}

ssize_t write_exact(int fd, void *buf, size_t len, int mayexit)
{
	ssize_t num = 0, written;

	while (len > 0 && !sigint) {
		if ((written = write(fd, buf, len)) < 0) {
			if (errno == EAGAIN && num > 0)
				continue;
			if (mayexit)
				return -1;
			else
				continue;
		}
		if (!written)
			return 0;
		len -= written;
		buf += written;
		num += written;
	}

	return num;
}