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

时间:2022-09-23 17:02:20
/*
* 题目:
* 请编写一个程序,设置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 -;
}
FILE *pfr = NULL;
pfr = fopen(path, "r");
if (pfr == NULL)
{
printf("fopen() failed ! file path:%s;error message:%s\n", path,
strerror(errno));
return -;
}
char buf[] = { };
while (fgets(buf, sizeof(buf), pfr) != NULL)
{
printf("%s", buf);
sleep();
memset(buf, , sizeof(buf));
}
fclose(pfr);
return ;
} 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 < )
{
printf("print file name!\n");
return -;
}
struct sigaction act;
act.sa_handler = handler;
//初始化信号集
sigemptyset(&act.sa_mask);
act.sa_flags = ;
//安装(注册)SIGINT和SIGQUIT信号
if (sigaction(SIGINT, &act, NULL) != )
{
printf("sigaction() failed !\n");
return -;
}
if (sigaction(SIGQUIT, &act, NULL) != )
{
printf("sigaction() failed !\n");
return -;
}
//阻塞信号
sigset_t bset;
//清空信号集
sigemptyset(&bset);
//将信号SIGINT和SIGQUIT添加到信号集中
sigaddset(&bset, SIGINT);
sigaddset(&bset, SIGQUIT);
//更改进程信号屏蔽状态字
if (sigprocmask(SIG_BLOCK, &bset, NULL) != )
{
printf("sigprocmask() failed !\n");
return -;
}
read_file(args[]);
//解除阻塞
if (sigprocmask(SIG_UNBLOCK, &bset, NULL) != )
{
printf("sigprocmask() failed !\n");
return -;
}
while()
{
pause();
}
return ;
}