新行字符未显示在proc文件中

时间:2014-02-01 00:37:55

标签: c linux vim linux-kernel kernel

所以我正在编写一个涉及写入proc文件的linux内核模块。不幸的是,换行符会出现问题。如果我用vim打开它,它显示为“num ^ @ num ^ @ num ^ @”。如果我抓住它,它会说“numnumnum”。它应该在每个“num”的末尾转到一个新行。

我将用于将每个条目写入proc文件的代码看起来似乎有点hacky。

    bufSize = snprintf(str,0,"%lu\n",var);
    str = (char*)kmalloc(bufSize*sizeof(char),GFP_KERNEL);
    snprintf(str,bufSize,"%lu\n",var);
    memcpy(msg+msglen,str,bufSize);
    msglen+=(bufSize);
    kfree(str);

我不知道字符串会有多长,所以第一个snprintf获取缓冲区所需的长度。初始化缓冲区,然后再次调用snprintf。然后将该字符串复制到msg,其中包含proc文件的数据。指针以现有消息的长度递增。

    int procfile_read(char *buffer, char **buffer_location, off_t offset, int
    buffer_length, int *eof, void *data) {

    int ret;

    printk(KERN_INFO "procfile_read (/proc/%s) called\n", PROCFS_NAME);

    if (offset > 0) {
    /* we have finished to read, return 0 */
    ret  = 0;
    } else {
     /* fill the buffer, return the buffer size */
    memcpy(buffer, msg, msglen);
    ret = msglen;
    }

    return ret;

这几乎是从教程中复制和粘贴的。

谢谢!

1 个答案:

答案 0 :(得分:0)

缓冲区大小太小

bufSize = snprintf(str,0,"%lu\n",var);
//                            + 1
str = (char*)kmalloc((bufSize + 1)*sizeof(char),GFP_KERNEL);
//                   + 1
snprintf(str,bufSize + 1,"%lu\n",var);
//                            + 1
memcpy(msg+msglen,str,bufSize + 1);
// no + 1 here
// Note that msglen is the string length.  Add 1 for the size needed.
msglen+=(bufSize);
kfree(str);
相关问题