4-5 signal (과제)

do·2022년 4월 28일
0

API

목록 보기
27/42

과제-1.
1. 처음 SIGUSR1 시그널을 수신하면 "SIGUSR1 first"를 출력하고,
두번째 SIGUSR1 시그널을 수신하면 "SIGUSR1 second"를 출력하고,
세번째 SIGUSR1 시그널을 수신하면 프로그램을 종료하는 프로그램을 구현하시오.
2. SIGTERM 시그널을 수신해도 프로그램은 종료되면 안된다. 프로그램은 3번째 SIGUSR1 시그널을 받을때만 종료되어야 한다.

수정
1. 핸들러 호출
2. sa_mask/sigemptyset/sigaddset/sigaction
집합에 넣은 시그널들은 봉쇄되어서, 핸들러가 진행될때 잠깐 막혔다가 핸들러 끝나면 처리됨
4. signal함수 위치
5. sigaction oldact는
기존에 시그널이 처리되던 방법을 구조체에 보관함
다시 불러올 수 있음

#include <stdio.h>
#include <stdlib.h> //exit()
#include <signal.h> //sig
#include <unistd.h> //pause()

void handler(int signo, siginfo_t *info, void *ucontext)
{
	static int count = 1;
	printf("count %d\n", count);
	printf("시그널 넘버 %d\n", info->si_signo);
	printf("에러 넘버 %d\n", info->si_errno);
	printf("시그널 발생 이유 %d\n", info->si_code);

	if (signo == SIGUSR1) {

		if (count == 1) {
			printf("SIGUSR1 first\n");
		}
		else if (count == 2) {
			printf("SIGUSR1 second\n");
		}
		else {
			printf("exit\n");
			exit(1);
		}

		count++;
	}

	sleep(10);
	//함수 끝나자마자 봉쇄된 시그널 처리됨
}

int main()
{
	if (signal(SIGTERM, SIG_IGN) == SIG_ERR) {
		perror("error\n");
		return 0;
	}

	struct sigaction act;
	act.sa_flags = SA_SIGINFO;
	act.sa_sigaction = handler;

	if (sigfillset(&act.sa_mask) == -1)
	{	
		perror("error\n");
		return 0;
	}

	if (sigaction(SIGUSR1, &act, NULL) == -1) {
		perror("error\n");
		return 0;
	}

	int j = 0;

	while (1) {
		printf("%d\n", j);
		sleep(1);
		j++;

		if (j > 10) {
			printf("j > 10\n");
			sigdelset(&act.sa_mask, SIGINT);
			break;
		}
	}

	int k = 0;
	while (1) {
		printf("%d\n", k);
		sleep(1);
		k++;
	}

	return 0;
}

0개의 댓글