Linux 下实现asynchronou notification

今天看到LLD3上的chapter6中的asynchronous notification这一节,想起了我之前的一个帖子。

http://www.oschina.net/question/158589_26587

那个时候,我其实就是想实现这种被动的通知,而不是主动的轮询。参考书上的例子,可以简单实现如下。

其原理,就是利用信号来实现一个event-driven的控制。

值得一提的是,并不是所有文件都支持asynchronous notification,通常socket和tty是支持的。

另外,如果想让自己的驱动支持asynchronous notification,必须要自己实现。方法参见LLD3 chapter6.

最重要的是如下几句话。

fcntl(STDIN_FILENO, F_SETOWN, getpid());
    fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | FASYNC);
//第一句,将stdio的owner设置为当前进程
//第二句,通知该文件的驱动,告诉它如果有数据可用,那么就通知这个file的owner
//完整示例程序如下。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>

int gotdata=0;
void sighandler(int signo)
{
    if (signo==SIGIO)
        gotdata++;
    return;
}

char buffer[4096];

int main(int argc, char **argv)
{
    int count;
    struct sigaction action;

    memset(&action, 0, sizeof(action));
    action.sa_handler = sighandler;
    action.sa_flags = 0;

    sigaction(SIGIO, &action, NULL);

    fcntl(STDIN_FILENO, F_SETOWN, getpid());
    fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | FASYNC);

    while(1) {
        /* this only returns if a signal arrives */
        sleep(86400); /* one day */
        if (!gotdata)
            continue;
        count=read(0, buffer, 4096);
        /* buggy: if avail data is more than 4kbytes... */
        write(1,buffer,count);
        gotdata=0;
    }
}

你可能感兴趣的:(linux,notification,asynchronous)