標籤:
1,在/proc檔案系統下建立節點的API
http://www.cnblogs.com/ziziwu/archive/2011/10/20/2218975.html
struct proc_dir_entry *create_proc_entry (const char *name, mode_t mode, struct proc_dir_entry *parent);
其中參數分別是 /proc 檔案名稱,掩碼,父目錄。
[cpp] view plaincopy
- 32 struct proc_dir_entry {
- 33 unsigned int low_ino;
- 34 umode_t mode;
- 35 nlink_t nlink;
- 36 kuid_t uid;
- 37 kgid_t gid;
- 38 loff_t size;
- 39 const struct inode_operations *proc_iops;
- 40 const struct file_operations *proc_fops;
- 41 struct proc_dir_entry *next, *parent, *subdir;
- 42 void *data;
- 43 atomic_t count; /* use count */
- 44 atomic_t in_use; /* number of callers into module in progress; */
- 45 /* negative -> it‘s going away RSN */
- 46 struct completion *pde_unload_completion;
- 47 struct list_head pde_openers; /* who did ->open, but not ->release */
- 48 spinlock_t pde_unload_lock; /* proc_fops checks and pde_users bumps */
- 49 u8 namelen;
- 50 char name[];
- 51 };
[cpp] view plaincopy
-
- 2,實現read和write proc檔案系統節點的函數,分別為read_proc和write_proc函數
- 原型函數:int (*read_proc)(char *page, char **start, off_t offset, int count, int *eof, void *data)
- 原型函數:typedef int (write_proc_t)(struct file *file, const char __user *buffer, unsigned long count, void *data);
http://blog.csdn.net/wbd880419/article/details/6637102
對於read_proc_t
1. 第一個參數:為啥叫page?答案就是如果對proc檔案調用讀操作,核心會分配一個頁大小的緩衝區。如何輸出大於一個頁的資料呢,這得依賴於第二個和第三個參數了。
為了理解第二三個參數,回憶下與檔案操作相關的系統調用:
int open(const char *pathname, int flags);
off_t lseek(int fildes, off_t offset, int whence);
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);
對於proc檔案,一次read操作最多隻能讀取一個page的資料,如果需要讀取大於一個頁的資料需要儲存read的傳回值,
然後使用lseek設定offset,然後再次調用read。回到參數的說明:
2. start和off參數:off對應於lseek裡面的offset(lseek whence為SEEK_END,offset為負 的情況下,傳進來的off為零,具體原因待考古)。
如果不設定*start的值,off的取值只能在[0, count - 1]之間,且能夠讀取的資料大小為:count - off。可以理解系統拷貝了
[page + off, page+count - 1]之間的資料到使用者的buffer裡。如果off的取值超出範圍,read將讀不到資料。
如果設定了*start的值,系統認為*start指向的地址就是off指定的地址,off的值會被忽略,系統會拷貝[start, start+count-1]之間的
資料到使用者空間。當然我們在實現start地址的定位時,可能會需要off的值。
3. count 參數與read中的count一致
4. eof參數,設定了這個參數表明不想再提供資料了,神馬意思呢?
如果不設定這個參數,對於上面說的start為空白的情況,read_proc返回後,系統如果發現 (count - off) < count
會接著下發寫請求,讀取off大小的資料。
例如:有這樣的讀取操作:
lseek(fd, 2, SEEK_SET); read(fd, buff_r, 30)
第一次調用read_proc, off=2, count=30, 由於我們沒有設定start的值,將讀取28位元組的資料,由於沒有設定*eof, 系統會再次下發read_proc
第二次調用read_proc, off=30, count=2, 在參數start的說明裡提到,對於這個調用,系統預設讀不到資料(怨念啊,為啥要下發)
於是read返回28
如果設定了這個參數就不會有第二次的下發了。
5. data參數,這個是給驅動程式預留的參數。
對於write_proc函數,參數是很簡單的,需要說明的只有一點,就是write_proc的第二個參數buffer是使用者態的地址,需要用copy_from_user
從使用者態把資料拷到核心態的緩衝區裡。
[linux驅動]proc學習筆記(一)