better error reports for Write()

pull/12/head
Tom Early 7 years ago
parent 067e347f34
commit 070684e123

@ -19,6 +19,9 @@
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
#include <string.h> #include <string.h>
#include <cstring>
#include <thread>
#include <chrono>
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <sys/socket.h> #include <sys/socket.h>
@ -93,22 +96,36 @@ ssize_t CUnixDgramWriter::Write(void *buf, size_t size)
// open the socket // open the socket
int fd = socket(AF_UNIX, SOCK_DGRAM, 0); int fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (fd < 0) { if (fd < 0) {
fprintf(stderr, "Failed to open socket %s\n", addr.sun_path+1); fprintf(stderr, "Failed to open socket %s : %s\n", addr.sun_path+1, strerror(errno));
return -1; return -1;
} }
// connect to the receiver // connect to the receiver
int rval = connect(fd, (struct sockaddr *)&addr, sizeof(addr)); int rval = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
if (rval < 0) { if (rval < 0) {
fprintf(stderr, "Failed to connect to socket %s\n", addr.sun_path+1); fprintf(stderr, "Failed to connect to socket %s : %s\n", addr.sun_path+1, strerror(errno));
close(fd); close(fd);
return -1; return -1;
} }
ssize_t written = -1; ssize_t written = 0;
while (written < 0) { int count = 0;
while (written <= 0) {
written = write(fd, buf, size); written = write(fd, buf, size);
if (written != (ssize_t)size) if (written == (ssize_t)size)
fprintf(stderr, "ERROR: only wrote %d bytes of %d to %s\n", (int)written, (int)size, addr.sun_path+1); break;
else if (written < 0)
fprintf(stderr, "ERROR: faied to write to %s : %s\n", addr.sun_path+1, strerror(errno));
else if (written == 0)
fprintf(stderr, "Warning: zero bytes written to %s\n", addr.sun_path+1);
else if (written != (ssize_t)size) {
fprintf(stderr, "ERROR: only %d of %d bytes written to %s\n", (int)written, (int)size, addr.sun_path+1);
break;
}
if (++count >= 100) {
fprintf(stderr, "ERROR: Write failed after %d attempts\n", count-1);
break;
}
std::this_thread::sleep_for(std::chrono::microseconds(5));
} }
close(fd); close(fd);

Loading…
Cancel
Save

Powered by TurnKey Linux.