min's devlog
alarm() 인터럽트 본문
alarm()
alarm()dms 시그널을 전달하기 위한 알림을 설정한다.
예를 들어, alarm 세팅 후 5초 경과시 sigalrm이라는 시그널이 발생했을 때 어떤 동작을 처리할지 코드를 작성하는 것이다.
alarm에 의한 read()의 인터럽트 확인
파일명:alarm_intr.c
컴파일: gcc-o alarm_intr alarm_intr.c
사용: alarm_intr
#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<errno.h>
void catch(int sig){ //시그널 핸들러
printf("time out\n");
return;
}
int main(int argc, char *argv[]){
int n;
char buf[128];
struct sigaction a;
a.sa_handler=catch; //catch라는 함수를 시그널 핸들러로 등록
a.sa_flags=0;
sigfillset(&a.sa_mask);
sigaction(SIGALRM,&a,NULL); //SIGALRM이 발생하면 catch함수 호출
alarm(5); //alarm 5초 세팅
puts("input of 5 second wait"); //화면에 띄울 것
n= read(0,buf,sizeof(buf)); //block상태임.
if(n>=0) //무엇인가 5초안에 키보드에서 입력들어옴
printf("%d byte read success\n",n);
else if(errno == EINTR) //그렇지 않다면 ctrl-c 없이도 알람발생->시그널핸들러
printf("read() interrupted\n"); //return 후 돌아와서 출력
else
perror("read fail");
alarm(0); //세팅이0이니까 이제 할 게 없다
return 0; //함수 끝
}
a.sa_handler=catch; 는 catch라는 함수를 시그널 핸들러로 등록하는 코드이다.
sigaction(SIGALRM,&a,NULL); sigaction 메소드에서 SIGALRM이 발생하면 catch함수를 호출한다.
alarm() 함수를 통해 5초로 세팅하고, puts() 함수는 화면에 띄울 메시지를 작성한다.(input of 5 second wait)
if 문에서 n이 0보다 크면 (5초안에 키보드에서 입력이 들어온게 있음) 성공 메시지를 출력하고,
그렇지 않다면 (입력이 없었다면) ctrl-c 를 누르지 않고도 알람을 발생시킨다. -> 시그널핸들러 작동
'Linux > TCP IP Socket Programming' 카테고리의 다른 글
파이프 기반의 프로세스간 통신 (0) | 2021.04.10 |
---|---|
SIGCHLD, wait() (0) | 2021.04.09 |
System Call 수행 중 함수 처리 (0) | 2021.04.09 |
System Call 수행 중의 시그널처리 (0) | 2021.04.09 |
Read 수행 중의 시그널처리 (0) | 2021.04.08 |
Comments