시작하기 전
C에서 현재 시간을 출력하는 방법
#include <stdio.h>
#include <time.h>
int main ()
{
time_t ct;
struct tm tm;
ct = time (NULL);
tm = *localtime (&ct);
printf ("%d-%d-%d hour: %d, min : %d, sec: %d\n",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
tm.tm_min, tm.tm_sec);
}
localtime 함수는 time_t 변수를 우리가 알아볼 수 있는 struct tm구조체로 변환해서 그 포인터를 넘겨준다.
따라서 *로 이 리턴값을 참조하여 struct tm 변수에 대입하였다.
tm.tm_year은 1900년 기준으로 0이므로 +1900을 해주면 우리가 원하는 연도를 얻을 수 있다.
tm.tm_mon의 경우는 +1을 해주어야 우리가 원하는 값을 얻을 수 있다.
나머지는 변수명 외에 특별한 것이 없다.
1. alarm
(1)
alarm(int n) 함수는 n 초후 자기 자신에게 SIGALRM이라는 시그널을 전달하는 함수이다.
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
void my_signal_handler(int signum)
{
printf("signum = %d\n", signum);
}
int main()
{
signal(SIGALRM, my_signal_handler);
alarm(5); // 5초 후 SIGALRM 시그널을 자기 자신에게 5초후 발생
while(1)
{
printf("Hello\n");
sleep(2);
}
return 0;
}
이렇게 주면 Hello가 출력되다가 SIGALRM 시그널을 프로세스 시작 후 5초 후에 받아 signal handler 가 실행되는 것을 볼 수 있다.
이를 이용하여 자기 자신에게 주기적으로 알람을 줄 수도 있다.
방법은 간단하다.
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
void my_signal_handler(int signum)
{
printf("signum = %d\n", signum);
alarm(5);
}
int main()
{
signal(SIGALRM, my_signal_handler);
alarm(5); // 5초 후 SIGALRM 시그널을 자기 자신에게 5초후 발생
while(1)
{
printf("Hello\n");
sleep(2);
}
return 0;
}
이렇게 시그널 핸들러에 alarm()을 추가해주면 된다.
'CS > 시스템 프로그래밍' 카테고리의 다른 글
[Linux] Thread (쓰레드) (2) | 2022.12.25 |
---|---|
[Linux] Semaphore (1) | 2022.12.08 |
[Linux] 공유 메모리를 이용한 데이터 교환 (0) | 2022.12.03 |
[Linux] 메시지 큐(message queue) (0) | 2022.12.02 |
[Linux] pipe의 개념 및 구현 (0) | 2022.11.30 |