Creating copy of existing strings would require allocation of new memory and then assign the old string to new one. The multiple steps required to create a string copy can be done with the help of a single function in the kernel.
Ref: Kernel API
In the example below, we have created a proc entry to show the usage of the function. A call to read the proc entry creates a copy of the existing string in temp allcates it to the string called copy which we send as output of the proc entry.
Save the file as proc_read_copy.c and compile it using the following makefile.
Compile and load the module into kernel using.
To see the output, read the proc entry created by the module.
Ref: Kernel API
In the example below, we have created a proc entry to show the usage of the function. A call to read the proc entry creates a copy of the existing string in temp allcates it to the string called copy which we send as output of the proc entry.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Tested on kernel 5.3*/ | |
#include <linux/module.h> | |
#include <linux/kernel.h> | |
#include <linux/proc_fs.h> | |
#include<linux/slab.h> | |
ssize_t size; | |
ssize_t read_proc(struct file *filp,char *buf,size_t count,loff_t *offp ) | |
{ | |
int ret; | |
char temp[6],*copy; | |
sprintf(temp,"hello"); | |
copy=kstrdup(temp,GFP_KERNEL); | |
printk(KERN_INFO "%s",copy); | |
size=sizeof(char)*strlen(copy); | |
ret = simple_read_from_buffer(buf,count,offp,copy,size); | |
return ret; | |
} | |
struct file_operations proc_fops = { | |
read: read_proc | |
}; | |
void create_new_proc_entry(void) | |
{ | |
proc_create("copy",0,NULL,&proc_fops); | |
} | |
int proc_init (void) { | |
create_new_proc_entry(); | |
return 0; | |
} | |
void proc_cleanup(void) { | |
remove_proc_entry("copy",NULL); | |
} | |
MODULE_LICENSE("GPL"); | |
module_init(proc_init); | |
module_exit(proc_cleanup); |
Save the file as proc_read_copy.c and compile it using the following makefile.
Compile and load the module into kernel using.
To see the output, read the proc entry created by the module.
Very nice examples, but shouldn't you release the allocated memory by using kfree? for both pointers: temp and copy. If you don't do that you will have memory leak in that process.
ReplyDeleteThank you for pointing it out.
DeleteUpdated to use of array, copy is not allocated using kmalloc so we cant use kfree on it
Delete