/*
*
asynctest.c: use async notification to read stdin
*
*
Copyright (C) 2001 Alessandro Rubini and Jonathan
Corbet
*
Copyright (C) 2001 O'Reilly & Associates
*
*
The source code in this file can be freely used,
adapted,
*
and redistributed in source or binary form, so long as
an
*
acknowledgment appears in derived source files.
The citation
*
should list that the code comes from the book "Linux
Device
*
Drivers" by Alessandro Rubini and Jonathan Corbet,
published
* by
O'Reilly & Associates. No warranty
is attached;
* we
cannot take responsibility for errors or fitness for
use.
*/
#include
#include
#include
#include
#include
#include
int gotdata=0; //全局flag,判断signal处理函数有没有执行;
void sighandler(int signo) //signal处理函数
{
if (signo==SIGIO)
gotdata++;
return;
}
char buffer[4096]; //全局buffer
int main(int argc, char **argv)
{
int count;
struct sigaction action;
//初始化
action
memset(&action, 0, sizeof(action));
action.sa_handler = sighandler;
action.sa_flags = 0;
sigaction(SIGIO, &action, NULL);//绑定action到SIGIO
signal
fcntl(STDIN_FILENO, F_SETOWN, getpid());//设置STDIN_FILENOD的owner为当前进程
fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | FASYNC);//设置STDIN_FILENO的文件状态标志(增加了FASYNC标志)。
while(1) {
/* this only returns if a signal arrives */
sleep(86400); /* one day */
//当SIGIO
signal来了,会将当前进程从sleep唤醒
if (!gotdata)
continue;
count=read(0, buffer, 4096);//从标准输入读数据
/* buggy: if avail data is more than 4kbytes...
*/
write(1,buffer,count);//向标准输出写数据
gotdata=0;
}
} |