#include #include #include "fns.h" int getmsg(int fd, char *buf, int n) { char num[4+1+1]; /* four digits, newline, nul */ int len, r; if(readn(fd, num, 5) != 5) { werrstr("read length: %r"); return -1; } num[5] = '\0'; len = strtoul(num, nil, 10); if(len < 0) { werrstr("unusual length"); return -1; } if(len >= n) { werrstr("too big for buffer: %d/%d", len, n); return -1; } r = readn(fd, buf, len); if(r < 0) return -1; if(r < len) { werrstr("short read: %d/%d", r, len); return -1; } buf[r] = '\0'; return len; } int sendmsg(int fd, char *s) { int n; n = strlen(s); if(fprint(fd, "%.4d\n", n) < 0 || write(fd, s, n) != n ) return -1; return n; }