簡體   English   中英

使用cat讀取字符設備驅動程序時參數無效

[英]Argument invalid when using cat to read a character device driver

當我嘗試使用以下方法讀取char設備時:

 cat /dev/fifodev

我收到來自終端的下一條消息

cat: /dev/fifodev: Invalid argument.

我已經創建了文件並授予了這樣的權限

sudo mknod /dev/fifodev c 251 0
sudo chmod 666 /dev/fifodev 

我的驅動程序代碼是:

/* 
 * Called when a process, which already opened the dev file, attempts to
 * read from it.
 */
static ssize_t device_read(struct file *filp,   /* see include/linux/fs.h   */
               char *buffer,    /* buffer to fill with data */
               size_t length,   /* length of the buffer     */
               loff_t * offset)
{
    char aux[BUF_LEN];

    printk(KERN_ALERT "Entering into device_read");

    if (size_cbuffer_t(buf)<length){
        return -EINVAL;
    }   

    remove_items_cbuffer_t (buf,aux, length);
    copy_to_user(buffer, aux, length);


    printk(KERN_ALERT "Getting out from device_read");

    return length;
}

我這里有什么問題? 為什么我不能在/ dev / fifodev文件中使用cat?

根據您的評論,您遇到的問題似乎是您的應用程序正在請求將數據讀取到大於要填充的數據的緩沖區中。

您將需要計算要復制的適當數據量(例如, lengthsize_cbuffer_t(buf)的較小值),並使用該值代替length

在函數原型緩沖區中,應將其稱為__user,以將其指定為用戶空間指針。 read方法的返回值是讀取的字符串的長度。 該函數會一直被召回,直到返回零為止。 我認為以下代碼將起作用。

    static ssize_t device_read(struct file *filp,   /* see include/linux/fs.h   */
               char __user *buffer,    /* buffer to fill with data */
               size_t length,   /* length of the buffer     */
               loff_t * offset)
{
    char aux[BUF_LEN];
    int byte_to_read,maxbyte;   
    printk(KERN_ALERT "Entering into device_read");
    /*
    if (size_cbuffer_t(buf)<length){
        return -EINVAL;
    }   
    */
    maxbyte=strlen(buf) - *offset; //considering buf is the pointer where you have data to copy to buffer(userspace)
    byte_to_read=maxbyte>length?length:maxbyte;
    if(byte_to_read==0)
    {
        printk(KERN_ALERT "Allready Read\n");
        return 0;
    }
    aux=buf;//as in your code AUX doesn't have anything. i'm supposing you want to copy data to this from buf and then use copy_to_user
    remove_items_cbuffer_t (buf,aux, length); //i have no idea why you have used this but i'm sure this wont create any problem
    copy_to_user(buffer, aux, length); //this will copy your data to userspace


    printk(KERN_ALERT "Getting out from device_read");

    return length;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM