内核已经提供了相应函数。实例如下:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
static char buf[] ="hello. \n";
static char buf1[100];
static u32 inflight_x[100] = {1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6,};
int __init hello_init(void)
{
struct file *fp;
loff_t pos;
ssize_t res = 0;
printk("hello enter/n");
fp = filp_open("/.../kernel_file.txt",O_RDWR | O_CREAT,0777);
if (IS_ERR(fp)){
printk("create file error/n");
return -1;
}
for (i=0;i<24;++i) {
len = sprintf(my_buf, "%u ", inflight_y[i]);
my_buf += len;
}
pos = 0;
res = kernel_write(fp, buf, sizeof(buf), &pos);
if (res < 0) {
printk("kernel_write error: %d\n", res);
return 0;
}
pos = 0;
res = kernel_read(fp, buf1, sizeof(buf), &pos);
if (res < 0) {
printk("kernel_write error: %d\n", res);
return 0;
}
printk("read: %s/n",buf1);
filp_close(fp,NULL);
return 0;
}
void __exit hello_exit(void)
{
printk("hello exit/n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");