瀏覽代碼

Add functions read_fully and write_fully. They are simpler alternatives to

read and write on blocking sockets.
master
Richard Nyberg 19 年之前
父節點
當前提交
38418fcd2b
共有 2 個文件被更改,包括 35 次插入0 次删除
  1. +32
    -0
      misc/subr.c
  2. +3
    -0
      misc/subr.h

+ 32
- 0
misc/subr.c 查看文件

@@ -174,3 +174,35 @@ rand_between(long min, long max)
{
return min + (long)rint((double)random() * (max - min) / RAND_MAX);
}

int
write_fully(int fd, const void *buf, size_t len)
{
ssize_t nw;
size_t off = 0;

while (off < len) {
nw = write(fd, buf + off, len - off);
if (nw == -1)
return errno;
off += nw;
}
return 0;
}

int
read_fully(int fd, void *buf, size_t len)
{
ssize_t nread;
size_t off = 0;

while (off < len) {
nread = read(fd, buf + off, len - off);
if (nread == 0)
return ECONNRESET;
else if (nread == -1)
return errno;
off += nread;
}
return 0;
}

+ 3
- 0
misc/subr.h 查看文件

@@ -24,4 +24,7 @@ int canon_path(const char *path, char **res);

long rand_between(long min, long max);

int read_fully(int fd, void *buf, size_t len);
int write_fully(int fd, const void *buf, size_t len);

#endif

Loading…
取消
儲存