用户空间和内核线程之间的共享内存 [英] Shared Memory between User Space and Kernel Threads

查看:611
本文介绍了用户空间和内核线程之间的共享内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个涉及kthreads的内核应用程序.我创建一个结构数组,并在用户空间中使用malloc分配内存.然后,我调用一个系统调用(已实现),并将数组的地址传递给内核空间.在系统调用的处理程序中,我创建了2个将监视数组的kthreads. kthread可以更改某些值,而用户空间线程也可以更改某些值.这个想法是使用数组作为共享内存.但是有些当我访问内核空间中的内存(使用copy_from_user)时,数据会以某种方式更改.我可以验证该地址在分配时和在内核中是否相同.但是,当使用copy_from_user时,它会提供各种值,例如垃圾值.

I am developing a kernel application which involves kthreads. I create an array of structure and allocate memory using malloc in user-space. Then I call a system call (which I implemented) and pass the address of array to kernel-space. In the handler of system-call I create I create 2 kthreads which will monitor the array. kthread can change some value and user-space threads can also change some values. The idea is to use the array as a shared memory. But some when I access the memory in kernel space (using copy_from_user) the data are somehow changed. I can verify that the address are same when it was assigned and in kernel. But when using copy_from_user it is giving various values like garbage values.

下面的语句还可以吗?

int kthread_run_function(void* data){
    struct entry tmp;
    copy_from_user(&tmp, data, sizeof(struct entry));
}

推荐答案

这不行,因为copy_from_user()是从 current 用户进程复制的(这很明显,因为没有办法告诉它是从哪个用户进程复制).

This is not OK because copy_from_user() copies from the current user process (which should be obvious, since there's no way to tell it which user process to copy from).

在您的用户空间进程调用的系统调用中,这是可以的,因为当前进程是您的用户空间进程.但是,在内核线程中,当前进程可能是系统上的任何其他进程-因此,您是从随机进程的内存中复制的,这就是为什么会出现垃圾的原因.

In a syscall invoked by your userspace process this is OK, because the current process is your userspace process. However, within the kernel thread the current process could be any other process on the system - so you're copying from a random process's memory, which is why you get garbage.

如果要在内核和用户空间进程之间共享内存,正确的方法是让 kernel 分配它,然后允许用户空间进程将其映射到其地址空间使用mmap().内核线程和用户空间进程将使用不同的指针来引用内存区域-内核线程将使用指针指向在内核地址空间内分配的内存,而用户空间进程将使用指针指向由<返回的内存区域c1>.

If you want to share memory between the kernel and a userspace process, the right way to do this is to have the kernel allocate it, then allow the userspace process to map it into its address space with mmap(). The kernel thread and the userspace process will use different pointers to refer to the memory region - the kernel thread will use a pointer to the memory allocated within the kernel address space, and the userspace process will use a pointer to the memory region returned by mmap().

这篇关于用户空间和内核线程之间的共享内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆