Linux Linux程序练习十三(信号阻塞,捕获)

/*
 * 题目:
 * 请编写一个程序,设置SIGINT和SIGQUIT信号,
 * 并在该程序中实现从文件中读取信息的操作,
 * 并保证在读取文件且只有在读取文件的过程中不会被发送的SIGINT和SIGQUIT信号所打断。
 * 提示:在文件读取前阻塞信号,在文件读取后解除阻塞。
 * */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <signal.h>

int read_file(const char *path)
{
    if (path == NULL)
    {
        printf("param not allow NULL!\n");
        return -1;
    }
    FILE *pfr = NULL;
    pfr = fopen(path, "r");
    if (pfr == NULL)
    {
        printf("fopen() failed ! file path:%s;error message:%s\n", path,
                strerror(errno));
        return -1;
    }
    char buf[1024] = { 0 };
    while (fgets(buf, sizeof(buf), pfr) != NULL)
    {
        printf("%s", buf);
        sleep(2);
        memset(buf, 0, sizeof(buf));
    }
    fclose(pfr);
    return 0;
}


void handler(int sign)
{
    if (sign == SIGINT)
    {
        printf("accept SIGINT !\n");
    } else if (sign == SIGQUIT)
    {
        printf("accept SIGQUIT !\n");
    } else
    {
        printf("accept other sign !\n");
    }
}


int main(int arg, char *args[])
{
    if (arg < 2)
    {
        printf("print file name!\n");
        return -1;
    }
    struct sigaction act;
    act.sa_handler = handler;
    //初始化信号集
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    //安装(注册)SIGINT和SIGQUIT信号
    if (sigaction(SIGINT, &act, NULL) != 0)
    {
        printf("sigaction() failed !\n");
        return -1;
    }
    if (sigaction(SIGQUIT, &act, NULL) != 0)
    {
        printf("sigaction() failed !\n");
        return -1;
    }
    //阻塞信号
    sigset_t bset;
    //清空信号集
    sigemptyset(&bset);
    //将信号SIGINT和SIGQUIT添加到信号集中
    sigaddset(&bset, SIGINT);
    sigaddset(&bset, SIGQUIT);
    //更改进程信号屏蔽状态字
    if (sigprocmask(SIG_BLOCK, &bset, NULL) != 0)
    {
        printf("sigprocmask() failed !\n");
        return -1;
    }
    read_file(args[1]);
    //解除阻塞
    if (sigprocmask(SIG_UNBLOCK, &bset, NULL) != 0)
    {
        printf("sigprocmask() failed !\n");
        return -1;
    }
    while(1)
    {
        pause();
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值