Ubuntu系統新增驅動
ubuntu裝置驅動是由裝載模組的方式進行的
2.6.x核心模組在http://www.ibm.com/developerworks/cn/linux/l-module26/上可以下載
按照定義建立驅動檔案
建立c檔案 Drive.c
int my_open(struct inode *inode, struct file *file);
int my_release(struct inode *inode, struct file *file);
ssize_t my_read(struct file *file, char __user *user, size_t t, loff_t *f);
ssize_t my_write(struct file *file, const char __user *user, size_t t, loff_t *f);
char message[MAX_SIZE] = "this is arafat(very shuai boy)'s Drive"; //開啟裝置時會顯示的訊息
int device_num;//裝置號
char* devName = "arafatsDrive";//裝置名
struct file_operations pStruct =
{
open:my_open,
release:my_release,
read:my_read,
write:my_write,
};
/* 註冊 */
int init_module()
{
int ret;
ret = register_chrdev(0, devName, &pStruct);
if (ret < 0)
{
printk("failed to register_chrdev.\n");
return -1;
}
else
{
printk("the lgsDrive has been registered!\n");
printk("id: %d\n", ret);
device_num = ret;
return 0;
}
}
//登出
void cleanup_module()
{
unregister_chrdev(device_num, devName);
printk("unregister successful.\n");
}
//開啟
int my_open(struct inode *inode, struct file *file)
{
printk("open lgsDrive OK!\n");
try_module_get(THIS_MODULE);
return 0;
}
//關閉
int my_release(struct inode *inode, struct file *file)
{
printk("Device released!\n");
module_put(THIS_MODULE);
return 0;
}
//讀裝置裡的資訊
ssize_t my_read(struct file *file, char __user *user, size_t t, loff_t *f)
{
if(copy_to_user(user,message,sizeof(message)))
{
return -2;
}
return sizeof(message);
}
//向裝置裡寫資訊
ssize_t my_write(struct file *file, const char __user *user, size_t t, loff_t *f)
{
if(copy_from_user(message,user,sizeof(message)))
{
return -3;
}
return sizeof(message);
}
相同目錄下建立 Makefile
obj-m := arafatsDrive.o #這裡是上面所建立的c檔名.o
PWD := $(shell pwd)
KERNELDIR := /usr/src/linux-4.9.84 #你要安裝mod的核心版本
all:
make -C $(KERNELDIR) M=$(PWD) modules
.PHONY: clean
clean:
rm -rf *.o *~ core *.ko *.mod.c modules.order Module.symvers
以下全部命令都得用root使用者
make
make完了以後用ls命令檢視 xxxx.ko是我們的驅動程式
用下面的命令裝在我們的模組
insmod xxxxxx.ko
利用lsmode命令可以檢視我們的裝置
這時候使用dmesg命令。可以檢視原始碼Drive.c中,設備註冊函式init_module()中的prink的輸出
cat /proc/devices
檢視自己裝置的裝置號
mknod /dev/Device c 243 0
上面命令來加入自己的裝置 Device為裝置名字 c 為字元型裝置 243為裝置號
然後使用 ls /dev就可以看到自己的裝置了
下面編寫測試程式test.c
int main(void) { int fd; char buf[MAX_SIZE]; //緩衝區 char get[MAX_SIZE]; //要寫入的資訊 char dir[50] = "/dev/arafatsDevice"; //裝置名 fd = open(dir, O_RDWR | O_NONBLOCK); if (fd != -1) { //讀初始資訊 read(fd, buf, sizeof(buf)); printf("%s\n", buf); //寫資訊 printf("input :"); gets(get); write(fd, get, sizeof(get)); //讀剛才寫的資訊 read(fd, buf, sizeof(buf)); printf("device Message: %s\n", buf); close(fd); return 0; } else { printf("Device open failed\n"); return -1; } }
測試成功
利用以下命令解除安裝裝置和模組
rm /dev/lgsDevice
rmmod lgsDrive
原文連結https://blog.csdn.net/ARAFATms/article/details/79397800