-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.c
More file actions
130 lines (105 loc) · 2.66 KB
/
Copy pathutil.c
File metadata and controls
130 lines (105 loc) · 2.66 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//
// util.c
// EchoServer
//
// Created by Gabriel Carrillo on 2/26/16.
// Copyright © 2016 Gabriel Carrillo. All rights reserved.
//
#include "util.h"
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define MAXLINE 512
int readn(int fd, char *ptr, int nbytes) {
int nleft, nread;
nleft = nbytes;
while (nleft > 0) {
nread = (int)read(fd, ptr, nleft);
if (nread < 0) {
return(nread);
} else if (nread == 0) {
break;
}
nleft -= nread;
ptr += nread;
}
return(nbytes - nleft);
}
int writen(int fd, char *ptr, int nbytes) {
int nleft, nwritten;
nleft = nbytes;
while (nleft > 0) {
nwritten = (int)write(fd, ptr, nleft);
if (nwritten <= 0) {
return(nwritten);
}
nleft -= nwritten;
ptr += nwritten;
}
return(nbytes - nleft);
}
int readline(int fd, char *ptr, int maxlen) {
int n, rc;
char c;
for (n = 1; n < maxlen; n++) {
if ((rc = (int)read(fd, &c, 1)) == 1) {
*ptr++ = c;
if (c == '\n') break;
} else if (rc == 0) {
if (n == 1) {
return 0;
} else {
break;
}
} else {
return -1;
}
}
*ptr = 0;
return n;
}
void str_echo(int sockfd) {
int n;
char line[MAXLINE];
for ( ; ; ) {
n = readline(sockfd, line, MAXLINE);
if (n == 0) {
return;
} else if (n < 0) {
// Handle error
fprintf(stderr, "str_echo: readline error");
exit(-1);
}
if (writen(sockfd, line, n) != n) {
// Handle error
fprintf(stderr, "str_echo: writen error");
exit(-1);
}
}
}
void str_cli(FILE *fp, int sockfd) {
int n;
char sendline[MAXLINE], recvline[MAXLINE + 1];
while (fgets(sendline, MAXLINE, fp) != NULL) {
n = (int)strlen(sendline);
if (writen(sockfd, sendline, n) != n) {
fprintf(stderr, "str_cli: writen error on socket");
exit(-1);
}
/*
* Now read a line from the socket and write it to
* our standard output.
*/
n = readline(sockfd, recvline, MAXLINE);
if (n < 0) {
fprintf(stderr, "str_cli: readline error");
exit(-1);
}
recvline[n] = 0;
fputs(recvline, stdout);
}
if (ferror(fp)) {
fprintf(stderr, "str_cli: error reading file");
exit(-1);
}
}