From 42a62db99c96d77fd6dc676b76705d8d90156c23 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Tam=C3=A1s=20F=C3=B6ldesi?= Date: Tue, 30 Jun 2015 19:06:28 +0200 Subject: [PATCH] Checking for closed peer connection before send --- src/common.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/common.c b/src/common.c index c2849420..7adbe2ea 100644 --- a/src/common.c +++ b/src/common.c @@ -44,6 +44,8 @@ #include #include +#include + #if HAVE_NETINET_IN_H # include #endif @@ -265,9 +267,23 @@ ssize_t swrite (int fd, const void *buf, size_t count) const char *ptr; size_t nleft; ssize_t status; + struct pollfd pfd; ptr = (const char *) buf; nleft = count; + + /* checking for closed peer connection */ + pfd.fd = fd; + pfd.events = POLLIN | POLLHUP | POLLRDNORM; + pfd.revents = 0; + if (poll(&pfd, 1, 0) > 0) { + char buffer[32]; + if (recv(fd, buffer, sizeof(buffer), MSG_PEEK | MSG_DONTWAIT) == 0) { + // if recv returns zero (even though poll() said there is data to be read), + // that means the connection has been closed + return -1; + } + } while (nleft > 0) { -- 2.30.2