commit dee986547578f20d4de344127c73112fe10312cc
parent 7ce7e02b536104b9399ff01b355a7f931e8527b2
Author: aabacchus <ben@bvnf.space>
Date: Sat, 12 Mar 2022 23:29:03 +0000
handle server shutdown properly
read returns 0 when the server has shutdown the socket.
also shutdown our writing end of the socket when stdin is EOF or an
error.
write(2) rather than printf(3) the received data.
Diffstat:
M | irC.c | | | 20 | +++++++++++++------- |
1 file changed, 13 insertions(+), 7 deletions(-)
diff --git a/irC.c b/irC.c
@@ -58,12 +58,17 @@ int main(int argc, char *argv[]) {
perror("poll");
return 1;
}
- if (fds[1].revents & POLLIN)
- if (sock_read(sfd) != 0)
+ if (fds[1].revents & POLLIN) {
+ int rec = sock_read(sfd);
+ if (rec < 0)
return 1;
+ else if (rec == 0) /* received EOF */
+ break;
+ }
if (fds[0].revents & POLLIN) {
char *line = NULL;
if (getline(&line, &linelen, stdin) == -1) {
+ shutdown(sfd, SHUT_WR);
free(line);
break;
}
@@ -78,6 +83,7 @@ int main(int argc, char *argv[]) {
free(line);
return 1;
}
+ shutdown(sfd, SHUT_WR);
free(line);
goto end;
case 'j':
@@ -173,14 +179,14 @@ int sock_write(int sfd, char *msg, ...){
int sock_read(int sfd){
unsigned char buff[BUF_LEN];
memset(&buff, 0, sizeof buff);
- ssize_t ret;
- ret = recv(sfd, buff, BUF_LEN, 0);
+ ssize_t ret = recv(sfd, buff, BUF_LEN, 0);
if (ret < 0) {
perror("sock_read");
- return 1;
+ return -1;
}
- printf("%s", buff);
- return 0;
+ //printf("%s", buff);
+ write(1, buff, ret);
+ return ret;
}