全部博文(165)
分类: LINUX
2012-06-12 17:22:47
#include #include #include #include #include #include MODULE_LICENSE("GPL"); #define MAJOR_NUM 254 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 = { read: globalvar_read, write: globalvar_write, }; static int global_var = 0; static struct semaphore sem; static wait_queue_head_t outq; static int flag = 0; static int __init globalvar_init(void) { int ret; ret = register_chrdev(MAJOR_NUM, "globalvar", &globalvar_fops); if (ret) { printk("globalvar register failure"); } else { printk("globalvar register success"); init_MUTEX(&sem); init_waitqueue_head(&outq); } return ret; } static void __exit globalvar_exit(void) { int ret; ret = unregister_chrdev(MAJOR_NUM, "globalvar"); if (ret) { printk("globalvar unregister failure"); } else { printk("globalvar unregister success"); } } static ssize_t globalvar_read(struct file *filp, char *buf, size_t len, loff_t *off) { //等待数据可获得 if (wait_event_interruptible(outq, flag != 0)) { return - ERESTARTSYS; } if (down_interruptible(&sem)) { return - ERESTARTSYS; } flag = 0; if (copy_to_user(buf, &global_var, sizeof(int))) { up(&sem); return - EFAULT; } up(&sem); return sizeof(int); } static ssize_t globalvar_write(struct file *filp, const char *buf, size_t len,loff_t *off) { if (down_interruptible(&sem)) { return - ERESTARTSYS; } if (copy_from_user(&global_var, buf, sizeof(int))) { up(&sem); return - EFAULT; } up(&sem); flag = 1; //通知数据可获得 wake_up_interruptible(&outq); return sizeof(int); } module_init(globalvar_init); module_exit(globalvar_exit); |
#include #include #include #include main() { int fd, num; fd = open("/dev/globalvar", O_RDWR, S_IRUSR | S_IWUSR); if (fd != - 1) { while (1) { read(fd, &num, sizeof(int)); //程序将阻塞在此语句,除非有针对globalvar的输入 printf("The globalvar is %d\n", num); //如果输入是0,则退出 if (num == 0) { close(fd); break; } } } else { printf("device open failure\n"); } } |
#include #include #include #include main() { int fd, num; fd = open("/dev/globalvar", O_RDWR, S_IRUSR | S_IWUSR); if (fd != - 1) { while (1) { printf("Please input the globalvar:\n"); scanf("%d", &num); write(fd, &num, sizeof(int)); //如果输入0,退出 if (num == 0) { close(fd); break; } } } else { printf("device open failure\n"); } } |
static ssize_t globalvar_read(struct file *filp, char *buf, size_t len, loff_t *off) { //获取信号量:可能阻塞 if (down_interruptible(&sem)) { return - ERESTARTSYS; } //等待数据可获得:可能阻塞 if (wait_event_interruptible(outq, flag != 0)) { return - ERESTARTSYS; } flag = 0; //临界资源访问 if (copy_to_user(buf, &global_var, sizeof(int))) { up(&sem); return - EFAULT; } //释放信号量 up(&sem); return sizeof(int); } |