0

私は持っている

#define IOCTL_ALLOC_MSG _IO(MAJOR_NUM, 0) 
#define IOCTL_DEALLOC_MSG _IO(MAJOR_NUM, 1)

ヘッダーファイルで。

そして、私が書いたドライバーファイルで:

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;
}

次のようなキャラクターファイルを作成しました

mknod /dev/memory c 60 0

アプリの呼び出しが失敗する

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;
            }
        }

アプリを実行すると、「ioctl failed. Return code: -1, means: Invalid argument」が表示されます: strerror(errno)

プリント:

Inserting memory module

参考までに、「/dev/memory」「memory」のさまざまな名前とメジャー番号の組み合わせを試してみましたが、無駄でした。

4

2 に答える 2

5

FILE*関数に aを渡していますがioctl()、ファイル記述子、つまりint.

少なくとも、ポインタをキャストせずに整数に変換しているという大きな警告を生成する必要がありますね。

明らかな解決策が 2 つあります。

  1. 関数を使用して、fileno()からファイル記述子を取得しますFILE*。のようなものになるはずですioctl(fileno(memfile), IOCTL_ALLOC_MSG)
  2. open()の代わりに使用しfopen()ます。低レベルのコードを書いている場合は、追加の抽象化レイヤーFILE*(すべてのバッファリングなど) を避けるため、これが推奨されるソリューションです。
于 2012-12-15T03:11:25.230 に答える
0

に変更fopen("memory")するfopen("/dev/memory1")と、コードの最初の問題が修正されると仮定します。

@SunEric はまた、あなたの質問に対するコメントでallocFunc()、ドライバーの初期化関数 ( memory_init()) で呼び出しを行っていることを指摘していますが、それはあなたがやりたいことのようIOCTL_ALLOC_MSGです。それは、あなたが解決しなければならない次の問題かもしれません。

于 2012-12-14T22:48:41.700 に答える