You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

命名管道未达最大容量时写入阻塞问题咨询

测试命名管道的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:02:11