linux设备驱动归纳总结(三):7.异步通知fasync
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
异步通知fasync是应用于系统调用signal和sigaction函数,下面我会使用signal函数。简单的说,signal函数就是让一个信号与与一个函数对应,没当接收到这个信号就会调用相应的函数。
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
一、什么是异步通知
个人认为,异步通知类似于中断的机制,如下面的将要举例的程序,当设备可写时,设备驱动函数发送一个信号给内核,告知内核有数据可读,在条件不满足之前,并不会造成阻塞。而不像之前学的阻塞型IO和poll,它们是调用函数进去检查,条件不满足时还会造成阻塞。
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
二、应用层中启用异步通知机制
其实就三个步骤:
1)signal(SIGIO,
sig_handler);
调用signal函数,让指定的信号SIGIO与处理函数sig_handler对应。
2)fcntl(fd,
F_SET_OWNER, getpid());
指定一个进程作为文件的“属主(filp->owner)”,这样内核才知道信号要发给哪个进程。
3)f_flags
= fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, f_flags | FASYNC);
在设备文件中添加FASYNC标志,驱动中就会调用将要实现的test_fasync函数。
三个步骤执行后,一旦有信号产生,相应的进程就会收到。
来个应用程序:
/*3rd_char_7/1st/app/monitor.c*/
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <fcntl.h>
5 #include <sys/select.h>
6 #include <unistd.h>
7 #include <signal.h>
8
9 unsigned int flag;
10
11 void sig_handler(int sig)
12 {
13 printf("<app>%s\n", __FUNCTION__);
14 flag = 1;
15 }
16
17 int main(void)
18 {
19 char buf[20];
20 int fd;
21 int f_flags;
22 flag = 0;
23
24 fd = open("/dev/test", O_RDWR);
25 if(fd < 0)
26 {
27 perror("open");
28 return -1;
29 }
30 /*三个步骤*/
31 signal(SIGIO, sig_handler);
32 fcntl(fd, F_SETOWN, getpid());
33 f_flags = fcntl(fd, F_GETFL);
34 fcntl(fd, F_SETFL, FASYNC | f_flags);
35
36 while(1)
37 {
38 printf("waiting \n"); //在还没收到信号前,程序还在不停的打印
39 sleep(4);
40 if(flag)
41 break;
42 }
43
44 read(fd, buf, 10);
45 printf("finish: read[%s]\n", buf);
46
47 close(fd);
48 return 0;
49 }
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
三、驱动中需要实现的异步通知
上面说的三个步骤,内核已经帮忙实现了前两个步骤,只需要我们稍稍实现第三个步骤的一个简单的传参。
实现异步通知,内核需要知道几个东西:哪个文件(filp),什么信号(SIGIIO),发给哪个进程(pid),收到信号后做什么(sig_handler)。这些都由前两个步骤完成了。
回想一下,在实现等待队列中,我们需要将一个等待队列wait_queue_t添加到指定的等待队列头wait_queue_head_t中。
在这里,同样需要把一个结构体struct
fasync_struct添加到内核的异步队列头(名字是我自己取的)中。这个结构体用来存放对应设备文件的信息(如fd,
filp)并交给内核来管理。一但收到信号,内核就会在这个所谓的异步队列头找到相应的文件(fd),并在filp->owner中找到对应的进程PID,并且调用对应的sig_handler了。
看一下fasync_struct
1097 struct fasync_struct {
1098 int magic;
1099 int
fa_fd;
1100 struct
fasync_struct *fa_next; /* singly linked list */ //一看就觉得他是链表
1101 struct
file *fa_file;
1102 };
上面红色标记说所的步骤都是由内核来完成,我们只要做两件事情:
1)定义结构体fasync_struct。
struct fasync_struct *async_queue;
2)实现test_fasync,把函数fasync_helper将fd,filp和定义的结构体传给内核。
108 int test_fasync (int fd, struct file *filp, int mode)
109 {
110 struct _test_t *dev = filp->private_data;
111
112 re