当前位置:网站首页>How to play with the reading and writing operations of blocking sockets?
How to play with the reading and writing operations of blocking sockets?
2022-07-01 12:41:00 【Tao song remains the same】
Blocking sockets Read and write operations , I referred to redis Source code , And then I made a change , It's comfortable to use :
/* ----------------- Blocking sockets I/O with timeouts --------------------- */
/* Redis performs most of the I/O in a nonblocking way, with the exception
* of the SYNC command where the slave does it in a blocking way, and
* the MIGRATE command that must be blocking in order to be atomic from the
* point of view of the two instances (one migrating the key and one receiving
* the key). This is why need the following blocking I/O functions.
*
* All the functions take the timeout in milliseconds. */
#define SYNCIO__RESOLUTION 10 /* Resolution in milliseconds */
/* Write the specified payload to 'fd'. If writing the whole payload will be
* done within 'timeout' milliseconds the operation succeeds and 'size' is
* returned. Otherwise the operation fails, -1 is returned, and an unspecified
* partial write could be performed against the file descriptor. */
ssize_t syncWrite(int fd, char *ptr, ssize_t size, long long timeout) {
ssize_t nwritten, ret = size;
long long start = mstime();
long long remaining = timeout;
while(1) {
long long wait = (remaining > SYNCIO__RESOLUTION) ?
remaining : SYNCIO__RESOLUTION;
long long elapsed;
/* Optimistically try to write before checking if the file descriptor
* is actually writable. At worst we get EAGAIN. */
nwritten = write(fd,ptr,size);
if (nwritten == -1) {
if (errno != EAGAIN) return -1;
} else {
ptr += nwritten;
size -= nwritten;
}
if (size == 0) return ret;
/* Wait */
aeWait(fd,AE_WRITABLE,wait);
elapsed = mstime() - start;
if (elapsed >= timeout) {
errno = ETIMEDOUT;
return -1;
}
remaining = timeout - elapsed;
}
}
/* Read the specified amount of bytes from 'fd'. If all the bytes are read
* within 'timeout' milliseconds the operation succeed and 'size' is returned.
* Otherwise the operation fails, -1 is returned, and an unspecified amount of
* data could be read from the file descriptor. */
ssize_t syncRead(int fd, char *ptr, ssize_t size, long long timeout) {
ssize_t nread, totread = 0;
long long start = mstime();
long long remaining = timeout;
if (size == 0) return 0;
while(1) {
long long wait = (remaining > SYNCIO__RESOLUTION) ?
remaining : SYNCIO__RESOLUTION;
long long elapsed;
/* Optimistically try to read before checking if the file descriptor
* is actually readable. At worst we get EAGAIN. */
nread = read(fd,ptr,size);
if (nread == 0) return -1; /* short read. */
if (nread == -1) {
if (errno != EAGAIN) return -1;
} else {
ptr += nread;
size -= nread;
totread += nread;
}
if (size == 0) return totread;
/* Wait */
aeWait(fd,AE_READABLE,wait);
elapsed = mstime() - start;
if (elapsed >= timeout) {
errno = ETIMEDOUT;
return -1;
}
remaining = timeout - elapsed;
}
}
/* Read a line making sure that every char will not require more than 'timeout'
* milliseconds to be read.
*
* On success the number of bytes read is returned, otherwise -1.
* On success the string is always correctly terminated with a 0 byte. */
ssize_t syncReadLine(int fd, char *ptr, ssize_t size, long long timeout) {
ssize_t nread = 0;
size--;
while(size) {
char c;
if (syncRead(fd,&c,1,timeout) == -1) return -1;
if (c == '\n') {
*ptr = '\0';
if (nread && *(ptr-1) == '\r') *(ptr-1) = '\0';
return nread;
} else {
*ptr++ = c;
*ptr = '\0';
nread++;
}
size--;
}
return nread;
}More conventional operation .
边栏推荐
- [20220605] Literature Translation -- visualization in virtual reality: a systematic review
- Friends day 2022
- What are the PHP FPM configuration parameters
- 类的初始化与实例化
- GID: open vision proposes a comprehensive detection model knowledge distillation | CVPR 2021
- Scene function of wooden frame
- 关于NAND FLASH解扣的认识
- Digital signal processing -- Design of linear phase (Ⅱ, Ⅳ) FIR filter (2)
- GPS 数据中的精度因子(DOP)与协方差之间的关系 (参考链接)
- Huawei interview question: Recruitment
猜你喜欢

codeforces -- 4B. Before an Exam

Ipv6-6to4 experiment

基因检测,如何帮助患者对抗疾病?

Four years after graduation: work, resign, get married, buy a house
![[20211129] configuration du serveur distant du carnet de notes jupyter](/img/7c/79c9fcb91bde75e954dc3ecf9f5afd.png)
[20211129] configuration du serveur distant du carnet de notes jupyter

BIM and safety in road maintenance-buildSmart Spain

工具箱之 IKVM.NET 项目新进展

leetcode:329. 矩阵中的最长递增路径【dfs + cache + 无需回溯 + 优雅】

How to use opcache, an optimization acceleration component of PHP
![[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world](/img/41/76687ea13e1722654b235f2cfa66ce.png)
[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world
随机推荐
【邂逅Django】——(二)数据库配置
I wish you all a happy reunion
Like the three foot platform
Ansible的playbook
Chained storage of queues
[datawhale202206] pytorch recommendation system: precision model deepfm & DIN
Mobile note application
Relationship between accuracy factor (DOP) and covariance in GPS data (reference link)
leetcode:241. Design priority for operation expression [DFS + Eval]
IOS interview
单点登录SSO与JWT好文整理
[20211129] jupyter notebook remote server configuration
Sort out relevant contents of ansible
Application of stack -- bracket matching problem
Fatal error: execution: there is no such file or directory
[brain opening] west tide and going to the world series
redis探索之缓存击穿、缓存雪崩、缓存穿透
CPI教程-异步接口创建及使用
Three stages of aho
leetcode:329. The longest incremental path in the matrix [DFS + cache + no backtracking + elegance]