函数scull_release()
void scull_release(struct inode *inode,struct file *filp)
{
MOD_DEC_USE_COUNT; // 该模块的用户数目减1
printk("This chrdev is in release\n");
return 0;
#ifdef DEBUG
printk("scull_release(%p,%p)\n",inode,filp);
#endif
}
测试函数源代码testproc.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "chardev.h" // 定义字符设备
void write_proc(void);
void read_proc(void);
main()函数
main(int argc,char **argv)
{
if(argc == 1) {
puts("syntax: testprog[write|read]\n");
exit(0);
}
if(!strcmp(argv[1], "write"))
{ write_porc(); }
else if(!strcmp(argv[1],"read"))
{ read_proc(); }
else
{ puts("testprog: invalid command!\n"); }
return 0;
}
write_proc()函数
void write_proc()
{
int fd,len,quit = 0;
char buf[100];
fd = open("/dev/chrdev",O_WRONLY);
if(fd <= 0) {
printf("Error opening device for writing!\n");
exit(1);
}
while(!quit) {
printf("\n Please write into:");
gets(buf);
if(!strcmp(buf,"exit"))
quit = 1;
(续)
while(ioctl(fd,DYNCHAR_QUERY_NEW_MSG))
usleep(100);
len = write(fd,buf,strlen(buf));
if(len < 0) {
printf("Error writing to device!\n");
close(fd);
exit(1);
}
printf("\n There are %d bytes written to device!\n",len);
}
close(fd);
}
read_proc()函数
void read_proc()
{
int fd,len,quit = 0;
char *buf = NULL;
fd=open("/dev/chrdev",O_RDONLY);
if(fd < 0) {
printf("Error opening device for reading!\n"");
exit(1);
}
while(!quit) {
printf("\n Please read out:");
while(!ioctl(fd,DYNCHAR_QUERY_NEW_MSG))
usleep(100); // 获取消息长度
(续)
len = ioctl(fd,DYNCHAR_QUERY_MSG_LENGTH,NULL);
if(len) {
if(buf != NULL)
free(buf);
buf = malloc(sizeof(char) * (len+1));
len = read(fd,buf,len);
if(len < 0) {
printf("Error reading from device!\n"); }
else {
if(!strcmp(buf,"exit") {
ioctl(fd,DYNCHAR_RESET); // 复位
quit = 1;
}
(续)
else
printf("%s\n",buf);
}
}
}
free(buf);
close(fd);
}