分类:
2005-09-29 10:44:15
/* ioproc.c - example code for i/o of proc file system
*
* Auth: zhou weicheng
* Date: 2005/9/28
*
* Usage: You can op /proc/msg_file after insmod this module, use cat, echo or vi, etc.
* echo "abc" > /proc/msg_file
* cat /proc/msg_file
*/
#include linux/kernel.h
#include linux/module.h
#include linux/proc_fs.h
#include linux/version.h
#include asm/uaccess.h
#define MAX_MSG_LENGTH 256
static char *filename = "msg_file";
struct proc_dir_entry *msg_entry = NULL;
static char msg_stored[MAX_MSG_LENGTH];
MODULE_PARM(filename, "s");
static ssize_t output_msg(
struct file *file,
char *buf,
size_t len,
loff_t *offset)
{
static int finished = 0;
int i;
if (finished) {
finished = 0;
return 0;
}
for (i = 0; i < len && msg_stored[i]; i++) {
put_user(msg_stored[i], buf + i);
}
printk("output buf: %s
", buf);
finished = i;
return i;
}
static ssize_t input_msg(
struct file *file,
char *buf,
size_t len,
loff_t *offset)
{
int i;
for (i = 0; i < MAX_MSG_LENGTH && i < len; i++) {
get_user(msg_stored[i], buf + i);
}
msg_stored[i] = ' ';
printk("input: %s
", msg_stored);
return i;
}
/*
* only root can write the file
* others can read
*/
static int check_perm(struct inode *i, int op)
{
printk("Check Permition
");
if ((op ==4) || ((op ==2) && (current->euid == 0))) {
return 0;
}
return -EACCES;
}
int open_msg(struct inode *i, struct file *f)
{
MOD_DEC_USE_COUNT;
return 0;
}
int close_msg(struct inode *i, struct file *f)
{
MOD_INC_USE_COUNT;
return 0;
}
static struct file_operations msg_fops =
{
read: output_msg,
write: input_msg,
open: open_msg,
release: close_msg,
};
static struct inode_operations msg_iops =
{
permission: check_perm
};
static int create_msg_file(void)
{
msg_entry = create_proc_entry(filename, S_IFREG | S_IRUGO | S_IWUSR, &proc_root);
if (!msg_entry) {
return -ENOMEM;
}
msg_entry->proc_fops = &msg_fops;
msg_entry->proc_iops = &msg_iops;
return 0;
}
static int del_msg_file(void)
{
remove_proc_entry(filename, &proc_root);
return 0;
}
module_init(create_msg_file);
module_exit(del_msg_file);