【发布时间】:2015-03-24 13:01:01
【问题描述】:
我在 Linux 下使用管道时遇到问题。我想填充管道以进一步阻止 write 的调用。其他进程应该能够从管道中读取一些应该允许其他进程写入的字符。
示例代码:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
int pipefd[2];
int size = 65535;
int total = 0;
// Create the pipe
if(pipe(pipefd) == -1)
{
perror("pipe()");
exit(EXIT_FAILURE);
}
// Fill in (almost full = 65535 (full - 1 byte))
while(total < size)
{
write(pipefd[1], &total, 1);
total++;
}
// Fork
switch(fork())
{
case -1:
perror("fork()");
exit(EXIT_FAILURE);
case 0:
// Close unused read side
close(pipefd[0]);
while(1)
{
// Write only one byte, value not important (here -> total)
int ret = write(pipefd[1], &total, 1);
printf("Write %d bytes\n", ret);
}
default:
// Close unused write side
close(pipefd[1]);
while(1)
{
int nbread;
scanf("%4i", &nbread);
char buf[65535];
// Read number byte asked
int ret = read(pipefd[0], buf, nbread);
printf("Read %d bytes\n", nbread);
}
}
return 0;
}
我不明白下面的行为。这个过程最后写了一个,因为我没有完全填满管道,正常。但之后,写入被阻塞(管道已满),任何读取都应解除阻塞等待的写入调用。
test@pc:~$./pipe
Write 1 bytes
4095
Read 4095 bytes
1
Read 1 bytes
Write 1 bytes
Write 1 bytes
Write 1 bytes
Write 1 bytes
Write 1 bytes
Write 1 bytes
...
相反,写入调用只有在读取 4096 字节后才会解除阻塞...为什么????
通常,在read 成功 X 字节后,管道中应该有 X 字节可用空间,因此 write 应该最多可以写入 X 字节,不是吗?
如何让行为“读取 1 个字节,写入 1 个字节等”而不是“读取 1 个字节,读取 1,读取 10,读取 2000,...(直到读取 4096 个字节),写入 4096”?
【问题讨论】: