/* * Salamander Server's Utility routines. * * G. Robert Malan (rmalan@eecs.umich.edu). * 2/25/97 * * $Id: salamanderUtil.c,v 1.8 1997/05/08 20:39:46 rmalan Exp $ */ #include #include #include #include /*********************************************************************** * * Routines used by both the server and various applications. * ***********************************************************************/ int readn(int fd, char *ptr, int nbytes) { int nleft, nread; nleft = nbytes; while(nleft > 0) { nread = read(fd, ptr, nleft); if (nread < 0) { if (errno == EAGAIN) { #if VERBOSE fprintf(stderr, "readn pausing for resouce.\n"); #endif sleep(1); continue; } #if VERBOSE fprintf(stderr, "readn failed (errno %d).\n", errno); #endif 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 = write (fd, ptr, nleft); if (nwritten <= 0) { if (errno == EAGAIN) { #if VERBOSE fprintf(stderr, "writen pausing for resouce.\n"); #endif sleep(1); continue; } #if VERBOSE fprintf(stderr, "writen failed (errno %d).\n", errno); #endif return (nwritten); } nleft -= nwritten; ptr += nwritten; } return (nbytes - nleft); } void timediff(struct timeval new, struct timeval old, struct timeval * diff) { diff->tv_usec = new.tv_usec - old.tv_usec; diff->tv_sec = new.tv_sec - old.tv_sec; if (diff->tv_usec < 0) { diff->tv_sec--; diff->tv_usec = 1000000 + diff->tv_usec; } } void generateTimestamp(char * timebuf) { struct timeval tv; gettimeofday(&tv, NULL); sprintf(timebuf, "%ld.%06ld", tv.tv_sec, tv.tv_usec); } /*********************************************************************** * * Routines only used by the various applications. * ***********************************************************************/ int readline(int fd, char *ptr, int maxlen) { int n, rc; char c; for (n = 1; n < maxlen; n++) { if ((rc = read(fd, &c, 1)) == 1) { *ptr++ = c; if (c == '\n') break; } else if (rc == 0) { if (n == 1) return (0); else break; } else { fprintf(stderr, "%d readline failed (errno %d).\n", errno); return (-1); } } *ptr = 0; return(n); } /* * Returns strlen + 1. */ int readstring(int fd, char *ptr, int maxlen) { int n, rc; char c; for (n = 1; n < maxlen; n++) { if ((rc = read(fd, &c, 1)) == 1) { *ptr++ = c; if (c == '\0') break; } else if (rc == 0) { if (n == 1) return (0); else break; } else { fprintf(stderr, "%d readstring failed (errno %d).\n", errno); return (-1); } } *--ptr = '\0'; /* In case we go over the maxlen. */ return(n); }