2012-10-19 35 views
7

我正在爲Linux寫一個設備驅動程序。它創建一個包含4個小號碼的設備。無論何時我們試圖以次要編號3寫入設備,我們都假設要終止設備,並且目前不會執行任何其他操作,除非它正在寫入booga設備。下面是我的一些當前的代碼,如果需要我可以發佈更多的代碼:Linux設備驅動程序,是否可以使用文件描述符獲取次要號碼?

Write方法:

static ssize_t booga_write (struct file *filp, const char *buf, size_t count, loff_t *f_pose) { 
    printk("Attempting to write to booga device\n"); 
    /* need to protect this with a semaphore if multiple processes 
     will invoke this driver to prevent a race condition */ 

    if (down_interruptible (&booga_device_stats->sem)) 
     return (-ERESTARTSYS); 
    booga_device_stats->num_bytes_written += count; 
    up(&booga_device_stats->sem); 
    return count; // pretend that count bytes were written 

} 

它是如何測試:

static void run_write_test(char *device, int bufsize) 
{ 
    char *buf; 
    int src; 
    int out; 

    src = open(device, O_WRONLY); 
    if (src < 0) { 
     perror("Open for write failed:"); 
     exit(1); 
    } 
    buf = (char *) malloc(sizeof(char)*(bufsize+1)); 
    fprintf(stderr, "Attempting to write to booga device\n"); 
    out = write(src, buf, bufsize); 
    fprintf(stderr, "Wrote %d bytes.\n", out); 
    free(buf); 
    close(src); 

} 

我想知道是否有一種方法獲取次要號碼。我查看了linux/fs.h,看到文件struct有一個名爲private_data的成員,但每當我嘗試調用它時,它都會使我的系統崩潰,因爲它當前設置爲null。

或者我應該不是試圖從結構文件中獲取次要編號,並應該在第一次打開設備時嘗試跟蹤它?

回答

13

你可以得到這樣的次要號碼,以便:

iminor(filp->f_path.dentry->d_inode) 
相關問題