-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrdwrn.c
74 lines (62 loc) · 2.46 KB
/
rdwrn.c
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
/*************************************************************************\
* Copyright (C) Michael Kerrisk, 2015. *
* *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU Lesser General Public License as published *
* by the Free Software Foundation, either version 3 or (at your option) *
* any later version. This program is distributed without any warranty. *
* See the files COPYING.lgpl-v3 and COPYING.gpl-v3 for details. *
\*************************************************************************/
/* Listing 61-1 */
/* rdwrn.c
Implementations of readn() and writen().
*/
#include <unistd.h>
#include <errno.h>
#include "rdwrn.h" /* Declares readn() and writen() */
/* Read 'n' bytes from 'fd' into 'buf', restarting after partial
reads or interruptions by a signal handlers */
ssize_t readn(int fd, void *buffer, size_t n)
{
ssize_t numRead; /* # of bytes fetched by last read() */
size_t totRead; /* Total # of bytes read so far */
char *buf;
buf = buffer; /* No pointer arithmetic on "void *" */
for (totRead = 0; totRead < n;) {
numRead = read(fd, buf, n - totRead);
if (numRead == 0) /* EOF */
return totRead; /* May be 0 if this is first read() */
if (numRead == -1) {
if (errno == EINTR)
continue; /* Interrupted --> restart read() */
else
return -1; /* Some other error */
}
totRead += numRead;
buf += numRead;
}
return totRead; /* Must be 'n' bytes if we get here */
}
/* Write 'n' bytes to 'fd' from 'buf', restarting after partial
write or interruptions by a signal handlers */
ssize_t writen(int fd, const void *buffer, size_t n)
{
ssize_t numWritten; /* # of bytes written by last write() */
size_t totWritten; /* Total # of bytes written so far */
const char *buf;
buf = buffer; /* No pointer arithmetic on "void *" */
for (totWritten = 0; totWritten < n;) {
numWritten = write(fd, buf, n - totWritten);
/* The "write() returns 0" case should never happen, but the
following ensures that we don't loop forever if it does */
if (numWritten <= 0) {
if (numWritten == -1 && errno == EINTR)
continue; /* Interrupted --> restart write() */
else
return -1; /* Some other error */
}
totWritten += numWritten;
buf += numWritten;
}
return totWritten; /* Must be 'n' bytes if we get here */
}