-
Notifications
You must be signed in to change notification settings - Fork 0
/
sock_util.c
82 lines (76 loc) · 1.33 KB
/
sock_util.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
75
76
77
78
79
80
81
82
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
void err_abort(char *msg)
{
fprintf(stderr, "%s\n", msg);
fflush(stdout);
fflush(stderr);
exit(1);
}
ssize_t readn(int fd, void *vptr, size_t n)
{
size_t nleft;
ssize_t nread;
char *ptr;
ptr = vptr;
nleft = n;
while( nleft > 0 ) {
if( (nread=read(fd, ptr, nleft)) < 0 ) {
if( errno == EINTR )
nread = 0; /* doit again */
else
return (-1);
} else if( nread == 0 ) {
break; /* EOF */
}
nleft -= nread;
ptr += nread;
}
return(n - nleft);
}
ssize_t writen(int fd, void *vptr, size_t n)
{
size_t nleft;
ssize_t nwritten;
char *ptr;
ptr = vptr;
nleft = n;
while( nleft > 0 ) {
if( (nwritten=write(fd, ptr, nleft)) <= 0 ) {
if( errno == EINTR )
nwritten = 0; /* doit again */
else
return(-1);
}
nleft -= nwritten;
ptr += nwritten;
}
return(n);
}
ssize_t readline(int fd, void *vptr, size_t maxlen)
{
ssize_t n, rc;
char c, *ptr;
ptr = vptr;
for( n=1; n<maxlen; n++ ) {
again:
if( (rc=read(fd, &c, 1)) == 1 ) {
*ptr++ = c;
if( c=='\n' )
break;
} else if( rc == 0 ) {
if( n == 1 )
return(0); /* EOF, no data */
else
break; /* EOF, some data */
} else {
if( errno == EINTR )
goto again; /* doit again */
return(-1); /* Error */
}
}
*ptr = '\0';
return(n);
}