본문 바로가기

[+] Information/[-] Network

[2009/09/24] 시그널 핸들링 예제소스(sigint.c, sigint2.c, sigalrm.c, zombie_handler.c)

/* sigint.c */

#include <stdio.h>
#include <unistd.h>
#include <signal.h>

void handler(int sig);

int main(int argc, char **argv)
{
  int state;
  int num=0;

  signal(SIGINT, handler);
  while(1)
  {
    printf("%d : 대기중 \n", num++);
    sleep(2);
    if(num>5)
      break;
  }
  return 0;
}

/*시그널 처리 함수 */
void handler(int sig)
{
  signal(SIGINT, handler);
  printf("전달된 시그널은 %d \n", sig);
}





/* sigint2.c */

#include <stdio.h>
#include <unistd.h>
#include <signal.h>

void handler(int sig);

int main(void)
{
  int state;
  int num=0;
 
  struct sigaction act;      /* 핸들러 구조체 변수 */
  act.sa_handler=handler;    /* 핸들러 함수 지정   */
  sigemptyset(&act.sa_mask); /* sm_mask의 모든 비트를 0으로 설정 */
  act.sa_flags=0;           

  state=sigaction(SIGINT, &act, 0); /* 시그널 핸들러 등록 */
  if(state != 0){
    puts("sigaction() error ");
    exit(1);
  }

  while(1){
    printf("%d : 대기중 \n", num++);
    sleep(2);
    if(num>5) break;
  }
  return 0;
}

/* 시그널 처리 함수 */
void handler(int sig)
{
  printf("전달된 시그널은 %d \n", sig);
}





/* sigalrm.c */

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>

void timer(int sig);

int main(int argc, char **argv)
{
  int state;

  struct sigaction act;
  act.sa_handler=timer;
  sigemptyset(&act.sa_mask);
  act.sa_flags=0;
 
  state=sigaction(SIGALRM, &act, 0); /* 시그널 핸들러 등록 */
  if(state != 0){
    puts("sigaction() error ");
    exit(1);
  }
 
  alarm(5); /* 5초 후에 SIGALRM 시그널 예약 */
  while(1){
    puts("대기중");
    sleep(2);
  }
  return 0;
}

void timer(int sig)
{
  puts("예약 하신 시간이 되었습니다!! \n");
  exit(0);
}





/* zombie_handler.c */

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

void z_handler(int sig);

int main(int argc, char **argv)
{
  pid_t pid;
  int state, i;

  struct sigaction act;
  act.sa_handler=z_handler;
  sigemptyset(&act.sa_mask);
  act.sa_flags=0;
 
  state=sigaction(SIGCHLD, &act, 0); /* 시그널 핸들러 등록 */
  if(state != 0){
    puts("sigaction() error ");
    exit(1);
  }
 
  pid=fork();
  if(pid==0) {
    printf("자식 프로세스 생성 : %d \n", getpid());
    exit(3);
  }
  else {
    sleep(3);
  }

  return 0; 
}

void z_handler(int sig)
{
  pid_t pid;
  int rtn;

  while( (pid=waitpid(-1, &rtn, WNOHANG)) > 0){
    printf("소멸된 좀비의 프로세스 ID : %d \n", pid);
    printf("리턴된 데이터 : %d \n\n", WEXITSTATUS(rtn));
  }
}