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

在实践中有个问题需要注意,设计将标准输入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 fcntl

void 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值