【问题标题】:Newline characters not showing up in proc fileproc文件中未显示换行符
【发布时间】:2014-02-01 00:37:54
【问题描述】:

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

无可否认,我将每个条目写入 proc 文件的代码似乎有点老套。

    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;

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

谢谢!

【问题讨论】:

    标签: c linux vim linux-kernel kernel


    【解决方案1】:

    缓冲区太小

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

    【讨论】:

    • 做到了。谢谢!我还是不太明白为什么你不在增量上加 1 但这行得通!
    • msglenlength 没有尾随 \0。它累积总长度,然后是memcpy() 的偏移量。该偏移量不需要 +1。
    • 原来的“num^@”(即“num\0”)出现是因为snprintf(str,bufSize,"%lu\n",var);太小了1,将\0放在bufSize-1位置,这是通过@复制的987654328@.
    猜你喜欢
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 2013-03-16
    • 2015-04-12
    相关资源
    最近更新 更多