信号驱动式I/O模型,以终端I/O为例写个demo

来源:互联网 发布:4glte网络优化前景如何 编辑:程序博客网 时间:2024/06/05 11:02

在实践中有个问题需要注意,设计将标准输入stdin来触发SIGIO信号,但发现标准输出stdout也能触发SIGIO信号,所以O_ASYNC应该是针对设备,而不是描述符。

如果在信号处理函数中,采用printf打印会不断触发SEGIO信号,所以改用写文件。


代码如下:

#include <stdio.h>#include <signal.h>#include <string.h>//for memset#include <unistd.h>//for STDIN_FILENO#include <fcntl.h>//for fcntlvoid sigio_handle(int sigio){    static count = 0;    count++;    FILE *fp = fopen("log", "a+");    if (NULL == fp)    {        perror("fopen error");        return;    }    fprintf(fp, "sigio_handle:count=%d\n", count);    fclose(fp);    return;}int main(){    int f1 = 0;    struct sigaction sa;    f1 = fcntl(STDIN_FILENO, F_GETFL, 0);    fcntl(STDIN_FILENO, F_SETFL, f1 | O_NONBLOCK | O_ASYNC);    fcntl(STDIN_FILENO, F_SETOWN, getpid());    sigemptyset(&sa.sa_mask);    sa.sa_flags = 0;    sa.sa_handler = sigio_handle;    if (sigaction(SIGIO, &sa, NULL) < 0)        perror("sigaction error");    while (1)    {        sleep(1);    }    return 0;}

 输入:

111
222
^C

log文件内容:

sigio_handle:count=1
sigio_handle:count=2
sigio_handle:count=3





0 0
原创粉丝点击