我有以下一段C代码,它从一个管道中读取,然后应该阻塞,但它从未阻塞过。
int pipe_fd;
int res;
int open_mode = O_RDONLY;
char buf[100];
int bytes_read = 0;
memset (buf, '\0', sizeof(buf));
pipe_fd = open(FIFO_NAME, open_mode);
if (access(FIFO_NAME, F_OK) == -1)
{
res = mkfifo(FIFO_NAME, 0777);
if (res != 0)
{
fprintf (stderr, "Could not create fifo %s\n", FIFO_NAME);
exit (EXIT_FAILURE);
}
}
for(;;)
{
do
{
res = read(pipe_fd, buf, sizeof(buf));
bytes_read += res;
}while (res > 0);
// process data then go back and block
............
}
在bash脚本中,通过类似'./test 1'的代码向服务器发送一个简单的缓冲区。
#!/bin/bash
pipe=/tmp/pipe
if [[ ! -p $pipe ]]; then
echo "Reader not running"
exit 1
fi
if [[ "$1" ]]; then
echo "some string" >$pipe
else
echo "q" >$pipe
fi
我在gdb中运行C代码程序,一开始它会因为read而阻塞,但是只要我调用bash脚本,C代码就不再阻塞了,并且成功从缓冲区读取数据,但每次读取时都读取了0字节,所以不确定为什么它不再阻塞。 "某个字符串" 数据在另一端被正确接收。
我只需要让它等待数据处理并返回等待更多数据。
open()
会分配新的文件描述符 - 旧的必须使用close()
释放。即使是写者在重新打开FIFO之前也会被阻塞。 - Dummy00001