volatile sig_atomic_t flag
로 선언하면 시그널의 일시적인 블록 없이 읽기, 쓰기를 안전하게 수행 할 수 있음
#include <stdio.h>
#include <stdlib.h> //exit()
#include <signal.h> //sig-
#include <unistd.h> //pause()
volatile sig_atomic_t flag = 0;
enum { CALL = 0, EXIT = -1 };
void log_message()
{
if (flag == 1) {
printf("SIGUSR1 first\n");
}
else if (flag == 2) {
printf("SIGUSR1 second\n");
}
else if (flag == 3){
printf("exit the program\n");
return EXIT;
}
return CALL;
}
void sigusr_handler(int signo)
{
if (signo == SIGUSR1) {
flag++;
}
}
int main()
{
struct sigaction act;
act.sa_handler = sigusr_handler;
act.sa_flags = 0;
if (sigaction(SIGUSR1, &act, NULL) != 0) {
perror("error\n");
return 0;
}
if (signal(SIGTERM, SIG_IGN) == SIG_ERR) {
perror("error\n");
return 0;
}
while (flag >= 0 && flag <= 2) {
pause();
if (log_message() != CALL) {
return 0;
}
}
return 0;
}