首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ioctl -参数无效

ioctl -参数无效
EN

Stack Overflow用户
提问于 2012-12-13 08:44:20
回答 2查看 15.4K关注 0票数 0

我有

代码语言:javascript
复制
#define IOCTL_ALLOC_MSG _IO(MAJOR_NUM, 0) 
#define IOCTL_DEALLOC_MSG _IO(MAJOR_NUM, 1)

在头文件中。

在驱动程序文件中,我写道:

代码语言:javascript
复制
struct file_operations memory_fops = {
  unlocked_ioctl: device_ioctl,
  open: memory_open,
  release: memory_release
};


int memory_init(void) {
  int result;

  /* Registering device */
  result = register_chrdev(MAJOR_NUM, "memory", &memory_fops);
  if (result < 0) {
    printk("<1>memory: cannot obtain major number %d\n", MAJOR_NUM);
    return result;
  }

  allocfunc();

  printk("<1>Inserting memory module\n");
  return 0;

}

int device_ioctl(struct inode *inode,   /* see include/linux/fs.h */
         struct file *file, /* ditto */
         unsigned int ioctl_num,    /* number and param for ioctl */
         unsigned long ioctl_param)
{
    /* 
     * Switch according to the ioctl called 
     */
    printk ( "<l> inside ioctl \n" );
    switch (ioctl_num) {
    case IOCTL_ALLOC_MSG:
        allocfunc();
        break;
    case IOCTL_DEALLOC_MSG:
        deallocfunc();
        break;
    }

    return 0;
}

我创建了角色文件,如下所示

代码语言:javascript
复制
mknod /dev/memory c 60 0

应用程序调用失败

代码语言:javascript
复制
int main(int argc, char *argv[]) {
    FILE * memfile;

    /* Opening the device parlelport */
    memfile=fopen("memory","r+");
    if ( memfile <0) {
        printf ( " cant open file \n");
        return -1;
    }

    /* We remove the buffer from the file i/o */
    int ret_val;
    if ( argc > 1 ) {
        if ( strcmp (argv[1], "mem" ) ==0 ) {


            ret_val = ioctl(memfile, IOCTL_ALLOC_MSG);

            if (ret_val < 0) {
                printf("ioctl failed. Return code: %d, meaning: %s\n", ret_val, strerror(errno));
                return -1;
            }
        }

当我运行应用程序时,在: strerror(errno)中得到"ioctl失败。返回代码:-1,意思是:无效参数“。

printk:

代码语言:javascript
复制
Inserting memory module

仅供参考,我尝试了"/dev/memory“"memory”不同的名称和主要数字组合--但都是徒劳的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-15 11:11:25

您正在向ioctl()函数传递一个FILE*,而它期望的是一个文件描述符,即一个int

它至少应该生成一个很大的警告,说明您正在将指针转换为整数,而不是强制转换,不是吗?

有两个显而易见的解决方案:

  1. 使用fileno()函数从FILE*获取文件描述符。它应该类似于ioctl(fileno(memfile), IOCTL_ALLOC_MSG).
  2. Use open(),而不是fopen()。如果您正在编写低级代码,则此方法是首选的解决方案,因为您可以避免FILE*强加的额外抽象层(所有缓冲内容等等)。
票数 5
EN

Stack Overflow用户

发布于 2012-12-15 06:48:42

我将假设将fopen("memory")更改为fopen("/dev/memory1")可以修复代码的初始问题。

@SunEric还在对你的问题的评论中指出,你在驱动程序的初始化函数(memory_init())中调用了allocFunc(),但这似乎是你想让你的IOCTL_ALLOC_MSG做的事情。这很可能是您需要解决的下一个问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13851212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档