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
91
92
93
94
95
| #include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <asm/uaccess.h>
#include <linux/wait.h>
#include <linux/semaphore.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include <linux/socket.h>
#include <linux/tcp.h>
#include <linux/proc_fs.h>
#include <net/net_namespace.h>
#include <net/tcp.h>
static ssize_t globalvar_read(struct file *, char *, size_t, loff_t*);
static ssize_t globalvar_write(struct file *, const char *, size_t, loff_t*);
struct file_operations globalvar_fops =
{
.owner = THIS_MODULE,
.read = globalvar_read,
.write = globalvar_write,
};
#define LEN 1024
static char global_var[LEN];
static int read_index = 0;
static int write_index = 0;
static spinlock_t var_lock;
static wait_queue_head_t waitq;
static int flag = 0;
static int major;
static const char procname[] = "testvar";
static int __init globalvar_init(void)
{
init_waitqueue_head(&waitq);
spin_lock_init(&var_lock);
// if (!proc_net_fops_create(&init_net, procname, S_IRUSR, &globalvar_fops)) {
if (!(major = register_chrdev(0, "globalvar", &globalvar_fops))) {
printk("globalvar register failure\n");
return -1;
}
printk("major = %d\n", major);
return 0;
}
static void __exit globalvar_exit(void)
{
// proc_net_remove(&init_net, procname);
unregister_chrdev(major, "globalvar");
}
static ssize_t globalvar_read(struct file *filp, char *buf, size_t len, loff_t *off)
{
int read_len;
//等待数据可获得
if (wait_event_interruptible(waitq, flag != 0))
return -ERESTARTSYS;
spin_lock(&var_lock);
read_len = write_index - read_index;
if (copy_to_user(buf, global_var+read_index, read_len)) {
spin_unlock(&var_lock);
return -EFAULT;
}
read_index = write_index;
flag = 0;
spin_unlock(&var_lock);
return read_len;
}
static ssize_t globalvar_write(struct file *filp, const char *buf, size_t len, loff_t *off)
{
spin_lock(&var_lock);
if (copy_from_user(global_var+write_index, buf, len)) {
spin_unlock(&var_lock);
return -EFAULT;
}
write_index += len;
spin_unlock(&var_lock);
flag = 1;
//通知数据可获得
wake_up_interruptible(&waitq);
return len;
}
module_init(globalvar_init);
module_exit(globalvar_exit);
MODULE_LICENSE("GPL");
|