0

我有一个在 linux 内核(3.2)中声明/定义的结构,我目前正在尝试在系统调用中分配这些结构之一,并为调用系统调用的进程返回一个指向它的指针。

  1. 我怎样才能#include在内核之外的程序中使用这个文件(问题可能是我应该包含哪个文件)?目前,我正在声明结构include/linux/syscalls.h并将其定义在我自己创建的文件中kernel/mysystemcall.c。如果我尝试在程序中使用该结构,我会得到error: dereferencing pointer to incomplete type.

  2. 考虑到如果我取消引用它,我如何才能真正从这个内存中读取它,我会得到一个分段错误?目前,我正在使用kmalloc分配内存;我需要打开一个标志来访问内存,还是应该使用其他东西来分配这个内存?

感谢您提供的任何帮助!

当前的系统调用实现:

#include <linux/linkage.h>
#include <linux/sched.h>
#include <linux/slab.h>

struct threadinfo_struct {
    int pid;
    int nthreads;
    int *tid;
};

asmlinkage struct threadinfo_struct *sys_threadinfo(void) {
    struct threadinfo_struct *info = kmalloc(sizeof(struct threadinfo_struct), GFP_KERNEL);
    info->pid = current->pid;
    info->nthreads = -1;
    info->tid = NULL;
    return info;
}

当前测试代码(外部内核):

#include <stdio.h>
#include <linux/unistd.h>
#include <sys/syscall.h>
#define sys_threadinfo 349

int main(void) {
    int *ti = (int*) syscall(sys_threadinfo);
    printf("Thread id: %d\n", *ti); // Causes a segfault
    return 0;
}

编辑:我意识到我可以让我的系统调用获取一个指向已分配内存的指针,并仅为用户填写值,但最好(教师偏好)以这种方式进行分配。

4

1 回答 1

2

看了这个答案后:

不要尝试从内核为用户空间分配内存——这严重违反了内核的抽象层。

在询问内核需要多少内存之后,我决定让用户空间程序自己分配内存。

这意味着我可以简单地将结构复制到用户和内核空间文件中,并且不需要#include内核文件来定义结构。

于 2013-02-24T18:54:22.710 回答