summaryrefslogtreecommitdiffstats
path: root/src/lib/read_write.c
blob: da067f78cc00864308ed64cd60eacf55ae292b01 (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
/*
 * Utility routines.
 *
 * Licensed under GPLv2 or later, see file COPYING in this tarball for details.
 */
#include "abrtlib.h"

/* Die with an error message if we can't read the entire buffer. */
void xread(int fd, void *buf, size_t count)
{
    if (count)
    {
        ssize_t size = full_read(fd, buf, count);
        if ((size_t)size != count)
            error_msg_and_die("short read");
    }
}

ssize_t safe_read(int fd, void *buf, size_t count)
{
    ssize_t n;

    do {
        n = read(fd, buf, count);
    } while (n < 0 && errno == EINTR);

    return n;
}

ssize_t safe_write(int fd, const void *buf, size_t count)
{
    ssize_t n;

    do {
        n = write(fd, buf, count);
    } while (n < 0 && errno == EINTR);

    return n;
}

ssize_t full_read(int fd, void *buf, size_t len)
{
    ssize_t cc;
    ssize_t total;

    total = 0;

    while (len)
    {
        cc = safe_read(fd, buf, len);

        if (cc < 0)
        {
            if (total)
            {
                /* we already have some! */
                /* user can do another read to know the error code */
                return total;
            }
            return cc; /* read() returns -1 on failure. */
        }
        if (cc == 0)
            break;
        buf = ((char *)buf) + cc;
        total += cc;
        len -= cc;
    }

    return total;
}

ssize_t full_write(int fd, const void *buf, size_t len)
{
    ssize_t cc;
    ssize_t total;

    total = 0;

    while (len)
    {
        cc = safe_write(fd, buf, len);

        if (cc < 0)
        {
            if (total)
            {
                /* we already wrote some! */
                /* user can do another write to know the error code */
                return total;
            }
            return cc;	/* write() returns -1 on failure. */
        }

        total += cc;
        buf = ((const char *)buf) + cc;
        len -= cc;
    }

    return total;
}

ssize_t full_write_str(int fd, const char *buf)
{
    return full_write(fd, buf, strlen(buf));
}