d82616520 发表于 2015-06-20 23:16

求解linux cat命令的实现机制!cat设备节点文件,没任何输出(之前已写入)

pipe设备:实现一个循环缓冲区阻塞读写

pipe0为设备节点

应用程序:
int main(int argc, char **argv)
{
int fd;
int err;
char wb = "today is good day!";
char wb1 = "what's the problem";
char rb ;
fd = open("/dev/pipe0", O_RDWR);//读写打开设备
if (fd < 0)
{
printf("can't open!\n");
}
printf("fd is : %d\n ",fd);
printf("%s\n", wb);
printf("%s\n", wb1);
   write(fd, &wb, 20);//写二次
write(fd, &wb1, 20);
   err=read(fd, &rb, 20);//读数据
printf("err is :%d\n", err);
   printf("%s\n", rb);//打印所读到数据

return 0;
}
应用程序Linux下运行结果:
root@book-desktop:/work/pipe# ./pipetest
fd is : 3
today is good day!
what's the problem
err is :20
today is good day!
root@book-desktop:/work/pipe#
root@book-desktop:/work/pipe#
root@book-desktop:/work/pipe# cat /dev/pipe0

^C
root@book-desktop:/work/pipe#
cat pipe0怎么什么都没有,是无数据还是阻塞,为什么?求大神讲解下cat的机制啊?

nswcfd 发表于 2015-06-25 21:14

应该跟cat没啥关系,cat的读写肯定都是block io。

可以strace确认一下,是block在open上,还是block在read上。

可以找一下fifo/pipe的实现,依稀记得,它对应的kernel buffer不是固定不变的,好像跟reader/writer的引用计数有关系。

如果你的程序不退出,在return 0之前加个pause,也许就能被外面的cat读到了。【不确定,自己做实验试试吧】static int fifo_open(struct inode *inode, struct file *filp)
{
        pipe = inode->i_pipe;
        if (!pipe) {
                pipe = alloc_pipe_info(inode);
                inode->i_pipe = pipe;
        }
        switch (filp->f_mode) {
        case 3:
        /*
       *O_RDWR
       *POSIX.1 leaves this case "undefined" when O_NONBLOCK is set.
       *This implementation will NEVER block on a O_RDWR open, since
       *the process can at least talk to itself.
       */
                filp->f_op = &rdwr_fifo_fops;
                pipe->readers++;
                pipe->writers++;
}               
const struct file_operations rdwr_fifo_fops = {
        .release        = pipe_rdwr_release,
};
static int pipe_rdwr_release(struct inode *inode, struct file *filp)
{
        int decr, decw;
        decr = (filp->f_mode & FMODE_READ) != 0;
        decw = (filp->f_mode & FMODE_WRITE) != 0;
        return pipe_release(inode, decr, decw);
}
static int pipe_release(struct inode *inode, int decr, int decw)
{
        pipe->readers -= decr;
        pipe->writers -= decw;
        if (!pipe->readers && !pipe->writers) {
                free_pipe_info(inode);
        }
}
页: [1]
查看完整版本: 求解linux cat命令的实现机制!cat设备节点文件,没任何输出(之前已写入)