标签:struct use sigaction sleep read fclose std fail 阻塞
/* * 题目: * 请编写一个程序,设置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; }
标签:struct use sigaction sleep read fclose std fail 阻塞
原文地址:http://www.cnblogs.com/zhanggaofeng/p/6119995.html