- 论坛徽章:
- 0
|
用于xsbase linux-2.4
一.编辑文件
1)模块文件
#vi xsbase.c
#define __NO_VERSION__
#include
#include
#include
#include
#include
#include
#include
#include
#include
static char *data;
unsigned int xsbase_major = 0;
static int xsbase_open(struct inode *inode, struct file *file);
static int xsbase_release(struct inode *inode , struct file *file);
static ssize_t xsbase_read(struct file *file, char *buf, size_t count, loff_t *f_pos);
static ssize_t xsbase_write(struct file *file, const char * buffer, size_t count, loff_t *f_pos);
static struct file_operations chr_fops = {
read: xsbase_read,
write: xsbase_write,
open: xsbase_open,
release: xsbase_release,
};
static int xsbase_open(struct inode *inode, struct file *file){
MOD_INC_USE_COUNT;
printk("this chrdev is opened!\n");
return 0;
}
static int xsbase_release(struct inode *inode, struct file *file){
MOD_DEC_USE_COUNT;
printk("this chrdev is released!\n");
return 0;
}
static ssize_t xsbase_read(struct file *file, char *buf, size_t count, loff_t *f_pos){
int len;
if (count
return -EINVAL;
len = strlen(data);
if (len
count = len;
copy_to_user(buf, data, count+1);
return count;
}
static ssize_t xsbase_write(struct file *file, const char * buffer, size_t count, loff_t *f_pos){
if (count
return -EINVAL;
kfree(data);
data = (char *)kmalloc(sizeof(char)*(count+1), GFP_KERNEL);
if (!data)
return -ENOMEM;
copy_from_user(data, buffer, count+1);
return count;
}
int init_module(void){
int res;
res = register_chrdev(0, "xsbase", &chr_fops);
if (res
printk("can't get major name!\n");
return res;
}
if(xsbase_major == 0)
xsbase_major = res;
return 0;
}
void cleanup_module(void){
unregister_chrdev(xsbase_major, "xsbase");
}
2)测试文件
#vi test_xsbase.c
#include
#include
#include
int
main(void)
{
int fd, length, rlen;
int i;
char *buf = "hello, world!\n";
char readbuf[12] = {0};
fd = open ("/dev/xsbase", O_RDWR);
if (fd
printf("Error opening device xsbase\n");
exit(1);
}
length = write (fd, buf, strlen(buf));
if (length
printf("Error writting to device xsbase\n");
exit(1);
}
rlen = read (fd, readbuf, 12);
if (rlen
printf("Error reading from device xsbase\n");
}
printf("the read result is %s\n", readbuf);
close(fd);
return 0;
}
二.编译
#arm-linux-gcc –c xsbase.c –I /…./2.4.18-rmk7-pxa1-XSBase255B/include –D__KERNEL__ -DMODULE // 2.4.18-rmk7-pxa1-XSBase255B 内核文件
#arm-linux-gcc test_xsbase.c –o test_xsbase
三.下载
下载这两个文件到板子上有两种方法:Zmodem 和 ftp。
四.运行
#cd /root
#insmod –f xsbase.o
#vi /proc/devices // 可以看到xsbase 253
#mknod /dev/xsbase c 253 0 // major 253 minor 0
#./test_xsbase // 可以看到测试结果
#rmmod xsbase
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/20871/showart_284625.html |
|