阅读:1309回复:4
设备文件为什么打不开?
我现在正在测试初建安装并调用module的实验.但有个小问题,还望解答:
我写了个module (test.c),并编译成功,而且安装,并创立了设备文件.但是运行test_app.c时,却显示cannot open file!. 我查了下 /dev/test文件,大小为0.请问到底哪里有问题? 是module(test.c) 还是test_app.c? 源码如下: [root@terrace root]# cat test.c #include<linux/kernel.h> #include<linux/module.h> #include<linux/fs.h> #include<asm/uaccess.h> static char *pMessage="just for test!aaaaaaaaaaaaaaaaaaaaaaaaa"; /* static struct file_operations test_fops={ read:test_read, write:test_write, open:test_open, release:test_release, }; */ static unsigned int test_major =0; static int test_read(struct file *file,char *buf,size_t length,loff_t *offset) { int bytes_read=0; if(*pMessage==0) return 0; while(length&& *pMessage){ put_user(*(pMessage++),buf++); length--; bytes_read++; } printk("<1>Read %d bytes,%d leftn",bytes_read,length); return bytes_read; } static size_t test_write(struct file *file,const char *buf,size_t length,loff_t *offset) { return -EINVAL; } static int test_open(struct inode *inode,struct file *fle) { MOD_INC_USE_COUNT; return 0; } static void test_release(struct inode *inode,struct file *file) { MOD_DEC_USE_COUNT; } static struct file_operations test_fops={ read:test_read, write:test_write, open:test_open, release:test_release, }; int init_module(void) { int result=register_chrdev(0,"test",&test_fops); if(result<0){ printk("<1>test:can't get major number!n"); return result; if (test_major==0) test_major=result; } return 0; } void clean_module(void) { unregister_chrdev(test_major,"test"); } [root@terrace root]# cat test_app.c #include<fcntl.h> #include<unistd.h> #include<stdio.h> int main() { int testdev; int i; char buf[20]; testdev=open("/dev/test",O_RDONLY); if(testdev =-1){ printf("cannot open file!n"); exit(0); } read(testdev,buf,20); for(i=0;i<20;i++) printf("%c",buf); close(testdev); } [root@terrace root]# |
|
沙发#
发布于:2004-02-19 19:21
要正确建立设备文件:
mknod /dev/test c 254 0 solution: (1)LDD2的第三章对这个问题有更明确的说明; (2)附件是LDD2中所有例子的程序; |
|
|
板凳#
发布于:2004-02-19 19:46
kernel_1998:
你真是我的大救星,我已经正确创建了设备文件,但还是有出现那个问题.(我已经给您回了信,请参阅详细情况!) 再次感谢! |
|
地板#
发布于:2004-02-20 09:44
static unsigned int test_major =0
你创建的设备文件号和这个要一致。 |
|
地下室#
发布于:2004-02-20 10:16
谢谢unix1998,我终于找到了问题所在!
原来问题极其简单,极其低级,实在是不好意思: 在user程序中,以前是: if(testdev=-1){ printf("cannot open file!\n"); exit(0); } 改成: if(testdev==-1){ printf("cannot open file!\n"); exit(0); } 就好了. 惭愧惭愧! 再次感谢! |
|