scull驱动模拟设备。编写读写设备的控制文件testscull.c向scull发送和接收数据。
1 安装scull.ko
在ldd3驱动源码文件夹中,进入scull文件夹,make,生成scull.ko,运行其中的shell文件:scull_load,完成scull.ko的安装。
# cd /sys/module/scull/parameters/
#cat scull_major
254
#cat scull_minor
0
可知scull.ko的主次设备号为254 0
进入/dev 创建设备文件:
#cd /dev
#mknod sculldev c 254 0
2 编写测试文件testscull.c
代码:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<error.h>
#include<fcntl.h>
#include<sys/types.h>
int main()
{
int fd,len;
char inbuf[20];
char outbuf[20]="scull dev test!";
fd=open("/dev/sculldev",O_WRONLY);
if(fd<0)
{printf("Error openning the device of sculldev for writing!/n");
exit(1);
}
len=write(fd,outbuf,strlen(outbuf)+1);
if(len<0)
{ printf("Error writing to the device!/n");
close(fd);
exit(1);
}
printf("writing %d bytes to the device!/n",len);
close(fd);
fd=open("/dev/sculldev",O_RDONLY);
if(fd<0)
{
printf("Error openning the device of sculldev for reading!/n");
exit(1);
}
len=read(fd,inbuf,len);
if(len<0)
{printf("Error reading from the device!/n ");
close(fd);
exit(1);
}
printf("reading %d bytes from the device!/n",len);
printf("%s/n",inbuf);
}
3 测试
#gcc testscull.c -o testscull
#./testscull
经过对scull_load的分析,其中包含了设备文件创建的代码,所以不用自己创建设备文件
#!/bin/sh
module="scull"
device="scull"
mode="664"
# invoke insmod with all arguments we got
# and use a pathname, as newer modutils don't look in . by default
/sbin/insmod ./$module.ko $* || exit 1
# remove stale nodes
rm -f /dev/${device}[0-3]
major=$(awk "//$2= =/"$module/" {print //$1}" /proc/devices)
mknod /dev/${device}0 c $major 0
mknod /dev/${device}1 c $major 1
mknod /dev/${device}2 c $major 2
mknod /dev/${device}3 c $major 3
# give appropriate group/permissions, and change the group.
# Not all distributions have staff, some have "wheel" instead.
group="staff"
grep -q '^staff:' /etc/group || group="wheel"
chgrp $group /dev/${device}[0-3]
chmod $mode /dev/${device}[0-3]