如何在内核 C 程序和用户级 C 程序之间共享数据?
我使用的是 Ubuntu 9.04,内核为 2.8.32。我创建了一个简单的系统调用,用于计算 克隆 和 execve 调用。当用户/shell 调用此系统调用时,我希望它将这两个值传递回用户。截至目前我正在使用:
#include <linux/sched.h>
#include <linux/asmlinkage>
/* These two variables are extern longs which are defined in sched.h and initialized in process_32.c */
total_execve;
total_clones;
long mycall* (int i){
int array[2];
array[0] = total_execve;
array[1] = total_clones;
return array;
}
我无法编译它,因为我得到了未定义的引用。
关于返回数组:我的新调用是否能够访问该数组,该数组不会位于内核内存中吗?
I am using Ubuntu 9.04 with kernel 2.8.32. I created a simple system call that counts the number of clone and execve calls. When the user/shell calls this system call, I would like it to pass back to the user these two values. As of now I am using:
#include <linux/sched.h>
#include <linux/asmlinkage>
/* These two variables are extern longs which are defined in sched.h and initialized in process_32.c */
total_execve;
total_clones;
long mycall* (int i){
int array[2];
array[0] = total_execve;
array[1] = total_clones;
return array;
}
I am not able to compile this as I get an undefined reference.
Regarding returning the array: Will my new call be able to access the array, won't the array be located in kernel memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要将指针返回到堆栈中。让调用者将指针传递到函数中。另外,您的函数声明语法不正确。这是您想要执行的操作:
Don't return pointers into the stack. Have the caller pass pointers into the function. Also, your function declaration syntax is incorrect. Here's what you want to do:
首先回答你的最后一个问题:数组确实位于“内核”内存中,但它是堆栈分配的,这意味着当 mycall() 函数退出时它将“消失”。您的函数可能看起来有效,但在内存快速重新使用的情况下可能会失败。
要返回多个值,常见的模式是调用者传递指向用户空间内存的指针,并让内核例程填充它们。例如,您可以为两个值传递两个指针,或者定义一个包含您需要的值并由内核例程填充的结构。
Answering your last question first: the array is indeed in "kernel" memory, but it's stack allocated which means it wilL "go away" when the mycall() function exits. Your function may appear to work, but may fail in cases where the memory gets re-used quickly.
To return multiple values, the common pattern is for the caller to pass in pointers to user-space memory, and have the kernel routine to fill them in. For example, you could pass in two pointers for your two values, or define a single struct that contains the values you need and gets filled in by the kernel routine.
您不能以这种方式返回数组。您需要声明 static 关键字来返回本地数组函数。你可以这样做:
You cannot return an array in this way. You need to declare static keyword to return a local array function. You could do something like this: