管道的容量是有限的。
如果管道已满,则 write(2) 将阻塞或者失败。
应用程序不应依赖于特定的容量:应用程序的设计应使读取进程在数据可用时立即消耗数据,以便写入进程不会一直阻塞。
在 2.6.11 之前的 Linux 版本中,管道的容量与系统页面大小相同(例如,i386 上的 4096 字节)。
自 Linux 2.6.11 起,管道容量为 16 页(即,在页面大小为 4096 字节的系统中为 65,536 字节)。
从 Linux 2.6.35 开始,默认管道容量为 16 页,但可以使用 fcntl(2) F_GETPIPE_SZ 和 F_SETPIPE_SZ 操作来查询和设置容量。
F_SETPIPE_SZ (int; since Linux 2.6.35) Change the capacity of the pipe referred to by fd to be at least arg bytes. An unprivileged process can adjust the pipe capacity to any value between the system page size and the limit defined in /proc/sys/fs/pipe-max-size (see proc(5)). Attempts to set the pipe capacity below the page size are silently rounded up to the page size. Attempts by an unprivileged process to set the pipe capacity above the limit in /proc/sys/fs/pipe-max-size yield the error EPERM; a privileged process (CAP_SYS_RESOURCE) can override the limit. When allocating the buffer for the pipe, the kernel may use a capacity larger than arg, if that is convenient for the implementation. (In the current implementation, the allocation is the next higher power-of-two page-size multiple of the requested size.) The actual capacity (in bytes) that is set is returned as the function result. Attempting to set the pipe capacity smaller than the amount of buffer space currently used to store data produces the error EBUSY. F_GETPIPE_SZ (void; since Linux 2.6.35) Return (as the function result) the capacity of the pipe referred to by fd.
为了验证这一点,让我们创建一个 fifo 管道文件
# mkfifo /tmp/testfifo
下面的python脚本(/tmp/change_fifo_size.py)可用于获取默认大小并将管道缓冲区大小增加到任何新值
#!/usr/bin/env python import signal import os import fcntl import sys F_SETPIPE_SZ = 1031 # Linux 2.6.35+ F_GETPIPE_SZ = 1032 # Linux 2.6.35+ def open_fifo(fifo): try: print "Checking fifo file ..." fifo_fd = open(fifo, "rb+") print "Pipe size : "+str(fcntl.fcntl(fifo_fd, F_GETPIPE_SZ)) fcntl.fcntl(fifo_fd, F_SETPIPE_SZ, 1000000) print "Pipe (modified) size : "+str(fcntl.fcntl(fifo_fd, F_GETPIPE_SZ)) return fifo_fd except Exception, e: print "Unable to create fifo, error: "+str(e) fifo_fd = open_fifo("/tmp/testfifo")
我们可以在此处根据要求替换突出显示的部分,例如:管道文件的位置和大小
执行上面的脚本
# /tmp/change_fifo_size.py Checking fifo file .... Pipe size : 65536 Pipe (modified) size : 1048576
所以默认的 fifo 文件大小是 64KB 增加到 1MB 。
日期:2020-06-02 22:18:32 来源:oir作者:oir