I created a kernel module and I want to communicate using a /proc file between the module and a script in python. I am using the Ubuntu 22.04 kernel version v5.15. I tried to create the /proc file in my module below:
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kdev_t.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/slab.h> // kmalloc()
#include <linux/uaccess.h> // copy_to/from_user()
#include <linux/proc_fs.h>
static struct proc_dir_entry *parent;
char etx_array[] = "hello how are you?";
int len = sizeof(etx_array) / sizeof(char);
static int open_proc(struct inode *inode, struct file *file)
{
pr_info("proc file opend.....\t");
return 0;
}
/*
* This function will be called when we close the procfs file
*/
static int release_proc(struct inode *inode, struct file *file)
{
pr_info("proc file released.....\n");
return 0;
}
/*
* This function will be called when we read the procfs file
*/
static ssize_t read_proc(struct file *filp, char __user *buffer, size_t length, loff_t * offset)
{
pr_info("proc file read.....\n");
if (copy_to_user(buffer, etx_array, len))
pr_err("Data Send : Err!\n");
return length;;
}
/*
* This function will be called when we write the procfs file
*/
static ssize_t write_proc(struct file *filp, const char *buff, size_t len, loff_t * off)
{
pr_info("proc file wrote.....\n");
if (copy_from_user(etx_array, buff, len))
pr_err("Data Write : Err!\n");
return len;
}
static struct proc_ops proc_fops = {
.proc_open = open_proc,
.proc_read = read_proc,
.proc_write = write_proc,
.proc_release = release_proc,
};
static int etx_driver_init(void)
{
proc_create("etx_proc", 0666, parent, &proc_fops);
return 0;
}
static void etx_driver_exit(void)
{
proc_remove(parent);
}
module_init(etx_driver_init);
module_exit(etx_driver_exit);
MODULE_LICENSE("GPL");
And if I try to use /proc file by python3
in user space like this:
import os
pf = open("/proc/etx_proc","r")
print(pf.read())
So I get this (running the python program):