summaryrefslogtreecommitdiffstats
path: root/lib/file-util.c
blob: a45c9468d888d01975d20edfcb45fd51330107e4 (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
/**
 * SPDX-License-Identifier: Apache-2.0
 *
 * @file	file-util.c
 * @brief	EINTR safe file functions
 */
#include "file-util.h"

#include <stdint.h>
#include <unistd.h>
#include <errno.h>

/**
 * INTR safe read
 * Interface spec is similar to read.
 */
ssize_t safe_read(int fd, void *buf, size_t count)
{
	ssize_t size = 0,ressize = 0;
	size_t reqsize = 0;
	uint8_t *pbuf = NULL;

	pbuf = (uint8_t*)buf;
	reqsize = count;

	do {
		size = read(fd, pbuf, (reqsize - ressize));
		if (size < 0) {
			if (errno == EINTR) {
				continue;
			} else {
				ressize = size;
				break;
			}
		}

		pbuf += size;
		ressize += size;
	} while((ressize < reqsize) && (size != 0));

	return ressize;
}

/**
 * INTR safe write
 * Interface spec is similar to read.
 */
ssize_t safe_write(int fd, void *buf, size_t count)
{
	ssize_t size = 0,ressize = 0;
	size_t reqsize = 0;
	uint8_t *pbuf = NULL;

	pbuf = (uint8_t*)buf;
	reqsize = count;

	do {
		size = write(fd, pbuf, (reqsize - ressize));
		if (size < 0) {
			if (errno == EINTR) {
				continue;
			} else {
				ressize = size;
				break;
			}
		}

		pbuf += size;
		ressize += size;
	} while((ressize < reqsize) && (size != 0));

	return ressize;
}