内核态下进行read/write系统调用的问题

写了一个模块,想在模块初始化时调用本地文件中的一些配置信息
但不知内核态下能不能调用open(),read()这些文件操作函数
写了一个小程序想验证,编译没有问题,但插入设备时报错:

[root@Vanillasky temp]# /sbin/insmod temp.o
temp.o: unresolved symbol errno
[root@Vanillasky temp]#

问题就出在这个errno,先看看我的程序吧(很简单的):

#if defined(CONFIG_SMP)
#define SMP
#endif

#if defined(CONFIG_MODVERSIONS)
#define MODVERSIONS
#include

 1<linux modversions.h="">   
 2#endif   
 3  
 4#include <linux kernel.h="">   
 5#include <linux module.h="">   
 6#include <linux stat.h="">   
 7#include <linux fcntl.h="">   
 8  
 9#define BUFLEN 50   
10  
11MODULE_LICENSE("GPL");   
12  
13#define __KERNEL_SYSCALLS__   
14#include <linux unistd.h="">   
15  
16  
17int init_module(void)   
18{   
19int fd,n;   
20char* buffer=NULL;   
21fd=open("/home/sophia/module/Hello",O_RDWR,S_IRWXU);   
22if((n=read(fd,buffer,BUFLEN))&lt;0) printk(KERN_DEBUG "Sophia: Read file error!\n");   
23printk(KERN_DEBUG "Sophia: Hello, kernel!\n");   
24printk(KERN_DEBUG "%s",buffer);   
25return 0;   
26}   
27void cleanup_module(void)   
28{   
29printk(KERN_DEBUG "Sophia: Good-bye, kernel!\n");   
30}   
31  
32编译:   
33gcc -D__KERNEL__ -I/usr/src/linux-2.4.20-8/include/ -DMODULE -Wall -O2 -c temp.c -o temp.o   
34没有错误   
35  
36我的程序本来是没有定义errno的。后来查了查,在linux/unistd.h里面有定义   
37extern int errno;但我include了这个文件的呀!   
38真搞不懂,怎么定义了的变量都会被系统认为是unresolved symbol?   
39  
40后来看了一下/proc/ksyms,发现跟errno有关的只有这一行:   
41c88143d0 journal_errno_R1f65a45f [jbd]   
42不知道跟我出现的问题有没有关系。   
43请大家不吝赐教,多谢!!   
44\---------------------------------------------------------------   
45  
46加上:   
47#ifndef __KERNEL__   
48#define __KERNEL__   
49#endif   
50  
51#ifndef MODULE   
52#define MODULE   
53#endif   
54试试看.   
55\---------------------------------------------------------------   
56  
57在内核中可以读写文件,但是不能直接调用open,read等函数。可以参考内核代码自己整理。   
58\---------------------------------------------------------------   
59  
60在unistd.h中只是申明不是定义   
61而内核又没有输出errno,所以需要自己定义一个   
62在include <unistd.h> 前定义一个int errno;就应该可以了   
63\---------------------------------------------------------------   
64  
65open read write是用户态的函数,在内核中是没有的,   
66标准的程序应该是这样的:   
67struct file *file = NULL;   
68mm_segment_t old_fs;   
69file = filp_open("/tmp/tmpfile", O_RDWR &amp;brvbarO_CREAT, 0666);   
70  
71old_fs = get_fs();   
72set_fs(get_ds());   
73if(file-&gt;f_op-&gt;write)   
74file-&gt;f_op-&gt;write(file,"12345",5, &amp;file-&gt;f_pos);   
75set_fs(old_fs);   
76  
77  
78OK..上面没有判断一些指针是否有效!!!   
79  
80\--------------------------------------------------------------   
81  
82搞定了,呵呵,果然要定义一个int errno   
83多谢各位!!</unistd.h></linux></linux></linux></linux></linux></linux>
Published At
Categories with 服务器类
Tagged with
comments powered by Disqus