命名管道未达最大容量时写入阻塞问题咨询
测试命名管道的write()阻塞行为
最近我在测试命名管道的写入阻塞逻辑,具体操作和思路如下:
- 先通过命令
mkfifo /tmp/pipe创建一个命名管道 - 每次向管道写入3字节数据,直到
write()函数被阻塞 - 我的系统里,管道的容量限制是16页(每页4096字节),按计算总容量应该是65536字节
我用下面的C代码来做这个测试:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <assert.h> #include <sys/types.h> #include <sys/wait.h> int main () { pid_t child; child = fork (); if (child == 0) { ssize_t ret; ssize_t total = 0; unsigned char *datat = malloc (65536); assert (datat != NULL); int fd = open ("/tmp/pipe", O_WRONLY); assert (fd != -1); while (1) { // 每次写入3字节数据 ret = write(fd, datat, 3); if (ret == -1) { perror("write failed"); break; } total += ret; // 打印已写入总字节数,方便观察阻塞时机 printf("Total written: %zd bytes\n", total); } free(datat); close(fd); exit(0); } else { // 父进程等待子进程执行完成 wait(NULL); } return 0; }
核心逻辑是让子进程持续向命名管道写入3字节数据,直到write()调用被阻塞——因为默认模式下,当管道被写满时,write()会阻塞,直到有进程读取管道数据腾出空间,这样就能验证管道的实际容量是否和预期一致。
内容的提问来源于stack exchange,提问作者sebastien dontneedtoknowthat
相关产品推荐
相关产品推荐

