1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
#include <asm/uaccess.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/kdev_t.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/wait.h>
static char devname[] = "sleep";
static char modname[] = "sleep.ko";
static dev_t mydev = 0;
static struct cdev cdev;
static int count = 0;
DECLARE_WAIT_QUEUE_HEAD(myqueue);
int sleep_open(struct inode *i, struct file *filp)
{
printk(KERN_ALERT "sleep_open: device (%d-%d) opened\n",
imajor(i), iminor(i));
printk(KERN_ALERT "sleep_open: mode %c%c\n", filp->f_mode & FMODE_READ ?
'R' : '-', filp->f_mode & FMODE_WRITE ? 'W' : '-');
return 0;
}
ssize_t sleep_read(struct file *filp, char __user *buf, size_t len,
loff_t *offset)
{
printk(KERN_ALERT "sleep_read: putting process %d (%s) to sleep...\n",
current->pid, current->comm);
count = 0;
if (wait_event_interruptible(myqueue, count))
return -ERESTARTSYS;
return 0;
}
ssize_t sleep_write(struct file *filp, const char __user *buf, size_t len,
loff_t *offset)
{
printk(KERN_ALERT "sleep_write: process %d (%s) brings salvation :D\n",
current->pid, current->comm);
count = 1;
wake_up_interruptible(&myqueue);
return -EPERM;
}
struct file_operations fops = {
.owner = THIS_MODULE,
.open = sleep_open,
.read = sleep_read,
.write = sleep_write,
};
static int __init sleep_init(void)
{
int err;
printk(KERN_ALERT "sleep_init: %s loaded by %s (%d)\n",
modname, current->comm, current->pid);
if ((err = alloc_chrdev_region(&mydev, 0, 1, devname)))
printk(KERN_ALERT "sleep_init: error %d in alloc_chrdev_region\n", err);
else
printk(KERN_ALERT "sleep_init: %s successfully registered with "
"%d %d numbers\n", devname, MAJOR(mydev), MINOR(mydev));
cdev_init(&cdev, &fops);
cdev.owner = THIS_MODULE;
if ((err = cdev_add(&cdev, mydev, 1)))
printk(KERN_ALERT "sleep_init: error %d in cdev_add\n", err);
return 0;
}
static void __exit sleep_exit(void)
{
unregister_chrdev_region(mydev, 1);
cdev_del(&cdev);
printk(KERN_ALERT "sleep_exit: %s unloaded\n", modname);
}
module_init(sleep_init);
module_exit(sleep_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Guillermo Ramos");
|