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]