alarm()関数を利用してSIGALRMシグナルを一定時間後に送信することができる。
SIGALRMをキャッチしない場合は、プロセスは終了する。SIGALRM以外のシグナルについては[C言語]シグナルをキャッチする サンプルコードを参照。
- alarm(int second);
- second秒数後にSIGALRMを送る
サンプルコード
#include <stdio.h>
#include <stdib.h> /* exit */
#include <unistd.h>
#include <signal.h>
void sigcatch(int);
int main() {
/* Set handler to SIGALRM */
if (SIG_ERR == signal(SIGALRM, sigcatch)) {
printf("failed to set signal handler.\n");
}
/* 5 seconds after, send signal */
alarm(5);
while (1) {
}
return 0;
}
void sigcatch(int sig) {
printf("catch signal %d\n", sig);
if (sig == SIGALRM) {
printf("catch SIGALRM and exit.\n");
exit(1);
}
}
実行結果
$ gcc alarm-sample.c
$ ./a.out
catch signal 14
catch SIGALRM and exit.
$ ./a.out
catch signal 14
catch SIGALRM and exit.
参考文献
![]() 入門UNIXシェルプログラミング |
![]() いますぐ始めるLinuxのC言語 |
![]() これならわかるC 入門の入門 |
参考URL
- MAN PAGE of ALARM
http://voyager.ise.osaka-sandai.ac.jp/JM/html/LDP_man-pages/man2/alarm.2.html - MAN PAGE of UALRM
http://www.linux.or.jp/JM/html/LDP_man-pages/man3/ualarm.3.html
実行環境
Linux Ubuntu 2.6.24, gcc version 4.2.3



