-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlines.c
88 lines (72 loc) · 1.7 KB
/
lines.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
83
84
85
86
87
88
#include <unistd.h>
#include <errno.h>
#include "lines.h"
// Funcion para mandar mensajes por sockets
int sendMessage(int socket, char * buffer, int len) {
int r;
int l = len;
do {
r = write(socket, buffer, l);
l = l - r;
buffer = buffer + r;
} while ((l > 0) && (r >= 0));
if (r < 0)
return (-1); /* fail */
else
return (0); /* full length has been sent */
}
// Función para recibir mensajes por sockets
int recvMessage(int socket, char * buffer, int len) {
int r;
int l = len;
do {
r = read(socket, buffer, l);
l = l - r;
buffer = buffer + r;
} while ((l > 0) && (r >= 0));
if (r < 0)
return (-1); /* fallo */
else
return (0); /* full length has been receive */
}
// Funcion para recibir cadenas en sockets
ssize_t readLine(int fd, void * buffer, size_t n) {
ssize_t numRead; /* num of bytes fetched by last read() */
size_t totRead; /* total bytes read so far */
char * buf;
char ch;
if (n <= 0 || buffer == NULL) {
errno = EINVAL;
return -1;
}
buf = buffer;
totRead = 0;
for (;;) {
numRead = read(fd, & ch, 1); /* read a byte */
if (numRead == -1) {
if (errno == EINTR) /* interrupted -> restart read() */
continue;
else
return -1; /* some other error */
} else if (numRead == 0) {
/* EOF */
if (totRead == 0) /* no byres read; return 0 */
return 0;
else
break;
} else {
/* numRead must be 1 if we get here*/
if (ch == '\n')
break;
if (ch == '\0')
break;
if (totRead < n - 1) {
/* discard > (n-1) bytes */
totRead++;
* buf++ = ch;
}
}
}
* buf = '\0';
return totRead;
}