如何使用copy_to_user从内核空间复制整数?

时间:2019-03-22 02:28:51

标签: c linux linux-kernel

问题

我无法复制数据。


用户空间

这是我的用户空间:

#include<stdio.h>
#include<stdlib.h>
#include<linux/kernel.h>
#include<sys/syscall.h>
#include<unistd.h>
#include<pwd.h>
#include<sys/sysinfo.h>

int main (int argc, char *argv[])
{
    void *mytask;
    short allsize;
    struct sysinfo si;
    struct passwd *passwdStruct;

    // to get the userid of my raspberry pi so i can see all of us processes

    const char * usrnm = argv[1];
    passwdStruct = getpwnam(usrnm);
    uid_t usrid = passwdStruct->pw_uid;

    // testing grabbing information 
    int holder = 7;
    void * ptr; // im making this a void pointer b/c copy_to_user takes a void * as parameter
    ptr = &holder;

    printf("old stuff: %d\n", holder);

    int sys_retval = syscall(398, usrid, allsize, ptr);

    printf("new stuff: \n");
    printf("p: %d\n", holder);

    return 0;
}

内核空间

这是我的内核空间:

#include<linux/kernel.h>
#include<linux/init.h>
#include<linux/sched.h>
#include<linux/syscalls.h>
//#include<linux/pwd.h> // includes the passwd struct which has id
//#include<sys/types.h> 
#include "mycall.h"
#include <linux/unistd.h>



asmlinkage long sys_sayhello(uid_t myusername, int siz, void __user *ptr)
{
    uid_t myid = myusername;
    const void *kern; // 2nd argument for copy_to_user
    struct task_struct *mytask;

// collect all the necessary info into the kernel array 
    for_each_process(mytask)
    {
        if (myid == mytask->cred->uid.val) // if the process belongs to the pi user
        {
            kern = &(mytask->pid); // I looked up kernel documentation and 
            copy_to_user(ptr, kern, sizeof(int)); // looks like pid is an INT type
            return;
        }
    }

    return 0;
}

输出

程序打印输出:

  

“旧资料:7   新内容:7英寸


问题

该数字应已更改为输出中我的pid进程的第一个pi。我该如何解决这个问题?

0 个答案:

没有答案