【问题标题】:how to receive the data by the user space application from the kernel space?用户空间应用程序如何从内核空间接收数据?
【发布时间】:2014-04-17 10:51:00
【问题描述】:

我正在计算 dev.c 内核源代码中的中断时间,如下所示:

extern double InterruptTime;
InterruptTime = ktime_get_real();   //timestamp

我正在使用 procfs 将数据从内核空间写入用户空间,并使用内核空间中的以下 api 将数据发送到用户空间。 PROCFS.c:

struct device {
double array[100];
}chr_arr;

ssize_t dev_read(struct file *filp,const char *buf,size_t count,loff_t *offset)
{
int len;
chr_arr.array =InterruptTime;         // Is this possible ??
len = count >= strlen(chr_arr.array) ? strlen(chr_arr.array) : count;
*offset += len; 
    if (*offset >= strlen(chr_arr.array))
        return 0;

    if (copy_to_user(buf,chr_arr.array,len))
        return -EFAULT;

    return len;
}

如上所示,是否可以从 PROCFS.c 中的 dev.c 读取 InterruptTime? 从上面内核代码发送的数据将如何在用户侧(即InterruptTime)接收??

【问题讨论】:

  • 返回用户空间代码是什么?每次读取只有一个char
  • InterruptTime 是我代码中的时间戳。我想将 InterruptTime 返回给用户。
  • 那么InterruptTime是什么类型的? extern char InterruptTime 表明它只是一个字符。您是在 chr_arr 中缓冲多个字符还是只缓冲一个字符? - 或者,更具体地说,sizeof(InterruptTime) 是什么?
  • InterruptTime 是 double 类型;所以我修改了上面的代码。这是访问 InterruptTime 的正确方法(我通过 procfs.c 程序从 dev.c 程序计算)?用户端如何接收InterruptTime?

标签: c linux linux-kernel client-server procfs


【解决方案1】:

我还不太确定,您是否只需要提供InterruptTime 的单个值,或者是否需要在生成这些值时缓冲这些值以供用户空间代码稍后检索。无需额外的缓冲工作,为简单起见,我建议以下内容:

ssize_t dev_read(struct file *filp,const char *buf,size_t count,loff_t *offset)
{

  if ( count < sizeof(InterruptTime) ) {
    // Not enough space provided.
    return 0; // Or some error code maybe.
  }

  if (copy_to_user(buf,&InterruptTime,sizeof(InterruptTime)) {
    return -EFAULT;
  } else {
    return sizeof(InterruptTime); // Number of bytes we copied.
  }

}

(请注意,这不是很干净,应该通过缓冲数据以允许读取任意大小、纠正错误处理等来改进。)

然后,在用户空间,你会做类似的事情

#include <fcntl.h>
...

int fd = open("/proc/...", O_RDONLY);

double timestamp;

loff_t dummyOffset;

if ( read( fd, &timestamp, sizeof(timestamp) ) != sizeof(timestamp) ) {
  // Failure.
} else {
  // Use value in timestamp...
}

...

【讨论】:

  • 非常感谢,但是在 dev.c 程序中计算的 InterruptTime 我在 PROCFS.c 程序中使用 ssize_t dev_read(struct file *filp,const char *buf,size_t count,loff_t *offset)到 1 :我想从 dev.c 读取 InterruptTime 并稍后传输到内核。从 PROCFS.c 程序访问 InterruptTime 是否正确?
  • 内核何时收到中断。将计算 InterruptTime 并稍后通过 PROCFS.c 程序将其发送给用户。我认为根据您的程序:我不想创建一个数组来存储中断时间。相反,我们可以直接从 dev.c 访问它的中断时间 - 对吗?
猜你喜欢
  • 1970-01-01
  • 2013-02-23
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-22
  • 2011-07-11
相关资源
最近更新 更多