linux 0.11 内核学习 pipe.c
/*
* 该文件中的两个函数read_pipe和write_pipe是上层函数
* read和write的底层实现
*/
/*
* linux/fs/pipe.c
*
* (C) 1991 Linus Torvalds
*/
#include <signal.h>
#include <linux/sched.h>
// 内存管理头文件。含有页面大小定义和一些页面释放函数原型
#include <linux/mm.h> /* for get_free_page */
#include <asm/segment.h>
/* pipe类似于队列,向pipe的尾部写入数据,从pipe的头部读取数据 */
/* 管道读操作函数 */
/* 参数inode 是管道对应的i 节点,buf 是数据缓冲区指针,count 是读取的字节数 */
/*
* read_pipe()函数用于读取管道中的数据,如果管道中没有数据的话,
* 唤醒写管道进程,自己睡眠,如果读到数据,并把数据传到用户缓冲区,
* 当把管道中所有的数据都取走后,也要唤醒等待写管道的进程,并返回
* 已读数据字节数
*/
int read_pipe(struct m_inode * inode, char * buf, int count)
{
int chars, size, read = 0;
while (count>0)
{
// 若当前管道中没有数据(size=0),则唤醒等待该节点的进程
while (!(size=PIPE_SIZE(*inode)))
{
wake_up(&inode->i_wait);
// 如果已没有写管道者
if (inode->i_count != 2) /* are there any writers? */
return read; // 返回已读字节数
// 否则在该i 节点上睡眠,等待信息
sleep_on(&inode->i_wait);
}
// 取管道尾到缓冲区末端的字节数chars
chars = PAGE_SIZE-PIPE_TAIL(*inode);
if (chars > count)
chars = count;
if (chars > size)
chars = size;
// 读字节计数减去此次可读的字节数chars,并累加已读字节数
count -= chars;
read += chars;
// 令size 指向管道尾部,调整当前管道尾指针(前移chars 字节)
size = PIPE_TAIL(*inode);
PIPE_TAIL(*inode) += chars;
PIPE_TAIL(*inode) &= (PAGE_SIZE-1);
// 将管道中的数据复制到用户缓冲区中
while (chars-->0)
put_fs_byte(((char *)inode->i_size)[size++],buf++);
}
// 唤醒等待该管道i 节点的进程
wake_up(&inode->i_wait);
// 返回读取的字节数
return read;
相关文档:
//
同步问题:
对共享数据的访问,需要同步,互斥。
在中断,抢占,多CPU,多线程 环境下尤其重要。
同步分为: 阻塞同步,非阻塞同步
阻塞同步有许多实现方式了:mutex, semaphore. 阻塞同步使用不当就可能造成死锁,活锁,优先级反转。
非阻塞同步:(现在流行三种)
wait free 很难实现,思想是本线程有限步就 ......
/*
* 该文件主要实现的是truncate函数,该函数是释放指定i
* 节点在设备上占用的所有逻辑块,包括直接块、一次间
* 接块和二次间接块
*/
/*
* linux/fs/truncate.c
*
* (C) 1991 Linus Torvalds
*/
#include <linux/sched.h>
......
/*
* 该文件实现系统调用read,write和lseek。
*/
/*
* linux/fs/read_write.c
*
* (C) 1991 Linus Torvalds
*/
#include <sys/stat.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/kernel.h>
#include < ......
/*
* linux/fs/char_dev.c
*
* (C) 1991 Linus Torvalds
*/
#include <errno.h>
#include <sys/types.h> // 定义了基本的系统数据类型
#include <linux/sched.h>
#include <linux/kernel.h> // 含有一些内核常用函数的原形定义
#include < ......