signal 예제. shell에서 kill -l로 해당 PID에 시그널을 보낼 수 있다.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
/* handler for SIGINT */
static void signal_hanlder (int signo)
{
/*
* Technically, you shouldn't use printf() in a
* signal handler, but it isn't the end of the
* world. I'll discuss why in the section
* "Reentrancy."
*/
if(signo == SIGINT){
printf ("Caught SIGINT!\n");
exit (EXIT_SUCCESS);
}
else if(signo == SIGCHLD){
printf ("SIGCHLD occured!\n");
//exit (EXIT_SUCCESS);
}
}
static void sigchld_handler (int signo)
{
/*
* Technically, you shouldn't use printf() in a
* signal handler, but it isn't the end of the
* world. I'll discuss why in the section
* "Reentrancy."
*/
printf ("SIGCHLD occured!\n");
//exit (EXIT_SUCCESS);
}
static void sighup_handler (int signo)
{
/*
* Technically, you shouldn't use printf() in a
* signal handler, but it isn't the end of the
* world. I'll discuss why in the section
* "Reentrancy."
*/
printf ("SIGHUP occured!\n");
printf ("ignoring SIGHUP\n");
if (signal(SIGHUP, SIG_IGN) == SIG_ERR){
fprintf (stderr, "Cannot ignore SIGHUP!\n");
exit (EXIT_FAILURE);
}
}
int main (void)
{
/*
* Register signal_hanlder as our signal handler
* for SIGINT.
*/
int pid;
if (signal (SIGINT, signal_hanlder) == SIG_ERR) {
fprintf (stderr, "Cannot handle SIGINT!\n");
exit (EXIT_FAILURE);
}
if (signal(SIGCHLD, signal_hanlder) == SIG_ERR){
fprintf (stderr, "Cannot handle SIGCHLD!\n");
exit (EXIT_FAILURE);
}
//signal hangup 등록
//주석 처리 후 run.. shell로 signal 전송.
//pi@raspberrypi:~ $ kill -1 pid
//하면
//pi@raspberrypi:~/Project/cCode/systemProgram $ rm ./a.out ;gcc signal.c ;./a.out
//I'm child, died
//SIGCHLD occured!
//끊어짐
//주석 처리하면
//pi@raspberrypi:~ $ kill -1 pid
//하면 무시함.
if (signal(SIGHUP, SIG_IGN) == SIG_ERR){
fprintf (stderr, "Cannot ignore SIGHUP!\n");
exit (EXIT_FAILURE);
}
//더 이어서..
//한번 sighup을 주면 메세지를 주고,
//두번째 받으면 무시되도록 작성.
if (signal(SIGHUP, sighup_handler) == SIG_ERR){
fprintf (stderr, "Cannot redefine SIGHUP!\n");
exit (EXIT_FAILURE);
}
pid=fork();
if(pid == 0){
//child process
printf("I'm child, died\n");
sleep(1);
_exit(EXIT_SUCCESS);
}
for (;;)
pause ();
return 0;
}