1
votes

My question is about usage and behavior of structs in Linux Kernel Space. I am writing a char device driver:

struct LEDs{

    int red_l;
};

ssize_t gmem_driver_write(struct file *file, const char *buf,
       size_t count, loff_t *ppos)
{

    struct LEDs myled;
    printk("Red is: %d \n", myled.red_l);       
    return 0;
}

static long my_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{

    struct LEDs myled = {};
    myled.red_l = 1;
    return 0;
}

If I call my_ioctl first and then write from user space, I am expecting red_l to have value 1 in struct LEDs and then I am expecting it to print inside write function. But it prints a garbage value.

My question: Since this logic works in user space, is there something different at play here ? What can be done to make it work in Linux Kernel Space ?

1
In both functions myled is a local variable inside the functions. Modifying them won't change anything else. Just like for non-kernel code. - Some programmer dude
In my non-kernel code, my struct is local to functions as well. Difference is, the in non-kernel mode, I can pass structs to the function where I want to access its content, in Kernel code, I cannot pass pointer to struct to write function from ioctl function. - Moose
I have tried putting structs in a header file as well to make the scope global. - Moose
That only make the structure "global", not the variables. You should probably get a few books and read more about scoping and life-time. - Some programmer dude
In the mentioned scenario, it is independent of the code for kernel space or user space as myled is a local variable within the respective functions. - Karthik Balaguru

1 Answers

4
votes

That logic does work the same in userspace as in kernelspace; i.e., it doesn't work at all in either. Declaring two variables with the same name in different functions doesn't make them the same variable.