#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h> /* for Pause(2) */
void action(int); /* signal handler */
int main(void)
{
int st;
struct sigaction test_sig;
memset(&test_sig, 0, sizeof(test_sig));
test_sig.sa_handler = action; /* 登録 */
sigaction(SIGINT, &test_sig, NULL); /* 実行 */
st = pause(); /* シグナル補足 */
return 0;
}
void action(int n)
{
/* 非同期シグナルの場合,安全ではない関数は呼ばないこと */
puts("\ncatch!"); // unsafe
}
/* ------------------------------------------------------
^D によりstdinが閉じられEOFが返る場合の対処例
--------------------------------------------------------- */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <unistd.h> /* for _exit(2) */
void sig_wait(void);
void bye(int dummy);
int main(void)
{
int c;
while((c=getchar()) != '\n') {
if(c == EOF) raise(SIGINT);
putchar(c);
}
puts("");
return 0;
}
/*
シグナルを補足
キー割り込みを補足する。
キー割り込みを補足した場合プログラムを終了
--------------------------------------------------- */
void sig_wait(void)
{
struct sigaction st_sig;
memset(&st_sig, 0, sizeof st_sig);
st_sig.sa_handler = bye;
sigaction(SIGINT, &st_sig, NULL);
}
/*
ステータス・コード 0(ゼロ)で終了する。
引数はダミー
--------------------------------------------------- */
void bye(int dummy)
{
_exit(0);
}