디시인사이드 갤러리

갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

Self-pipe 기법을 이용한 Ada 시그널 핸들러 (코드 리뷰 부탁)

나르시갤로그로 이동합니다. 2025.07.24 09:15:29
조회 68 추천 0 댓글 2

제목: Self-pipe 기법을 이용한 Ada 시그널 핸들러 (코드 리뷰 부탁드립니다) 🚀

안녕하세요, Ada로 시스템 프로그래밍을 공부하고 있는 개발자입니다.

최근 유닉스(POSIX) 환경에서 시그널을 좀 더 안전하고 Ada스럽게 처리하는 라이브러리를 만들어보고 있습니다. 특히 시그널 핸들러의 비동기-안전(async-signal-safety) 문제를 해결하기 위해 self-pipe 기법을 적용해 보았는데, 다른 분들의 의견은 어떨지 궁금해서 코드를 공유하고 피드백을 요청합니다.

## 주요 설계

이 라이브러리의 핵심 설계는 다음과 같습니다.

  1. Self-Pipe 기법: 실제 시그널 핸들러에서는 write() 시스템 콜만으로 시그널 번호를 파이프에 쓰는 최소한의 작업만 수행합니다. 복잡한 로직은 모두 메인 이벤트 루프에서 파이프를 read()하는 dispatch 프로시저로 옮겨, 비동기-안전 제약 조건에서 벗어나도록 설계했습니다.
  2. 스레드-안전 핸들러 관리: 시그널 번호와 사용자 정의 핸들러를 매핑하는 자료구조를 protected object로 감싸, 멀티스레드 환경에서도 안전하게 핸들러를 등록하고 호출할 수 있도록 했습니다.
  3. 자동 자원 관리 (RAII): Ada.Finalization을 이용해 패키지 스코프가 종료될 때 생성된 파이프의 파일 디스크립터가 자동으로 close 되도록 구현하여 리소스 누수를 방지했습니다.

## 특징

  • 비동기-안전(Async-Signal-Safe) 시그널 처리
  • Ada의 강력한 타입을 활용한 안전한 API (Action 레코드, Number 타입 등)
  • 스레드-안전(Thread-Safe) 핸들러 등록 및 관리
  • 자동 자원 해제 (RAII)

## 고민되는 부분 및 질문

현재 dispatch 프로시저의 read 로직이 아직 미흡합니다. 지금 코드는 read의 반환 값이 0 이하이면 무조건 루프를 빠져나가는데, 이렇게 되면 논블로킹(non-blocking) I/O에서 정상적으로 발생하는 EAGAIN 같은 상황에 제대로 대처하지 못합니다.

bytes_read < 0일 때 errno를 확인해서 EAGAIN이나 EINTR 같은 경우를 구분하고, 실제 I/O 에러일 때는 예외를 던지는 식으로 개선해야 할 것 같은데, 이 부분에 대한 더 좋은 아이디어나 일반적인 처리 패턴이 있다면 조언 부탁드립니다!

## 전체 코드

-- clair-signal.adb
-- Copyright (c) 2025 Hodong Kim <hodong@nimfsoft.art>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

with Interfaces.C;
with System;
with Clair.Error;
with Ada.Containers.Hashed_Maps;
with Ada.Finalization;
with Ada.Unchecked_Conversion;
with unistd_h;
with signal_h;
with sys_signal_h; -- For the C sigaction type
with errno_h;
with sys_types_h;
with Clair.Config;

package body Clair.Signal is
  use type Interfaces.C.Int;
  use type Interfaces.C.long;
  use type Interfaces.C.Unsigned;
  use type Interfaces.C.Unsigned_Long;
  use type Clair.File.Descriptor;

  -- Internal state for the self-pipe
  pipe_fds : aliased array (0 .. 1) of Clair.File.Descriptor := (-1, -1);

  -- pipe() 함수에 전달할 포인터 타입을 정의합니다.
  type C_Int_Access is access all Interfaces.C.int;

  -- System.Address를 C_Int_Access 타입으로 변환하는 함수를 인스턴스화합니다.
  function to_c_int_access is new Ada.Unchecked_Conversion
    (source => System.Address,
     target => C_Int_Access);

  -- The actual signal handler that will be r e g i s t e r e d with the kernel
  procedure clair_signal_handler
    (signo   : Interfaces.C.Int;
     info    : access sys_signal_h.siginfo_t;
     context : System.Address);
  pragma export (c, clair_signal_handler, "clair_signal_handler");

  procedure clair_signal_handler
    (signo   : Interfaces.C.Int;
     info    : access sys_signal_h.siginfo_t;
     context : System.Address)
  is
    signo_val     : aliased Interfaces.C.Int := signo;
    bytes_written : Interfaces.C.long;
  begin
    -- This is async-signal-safe
    bytes_written :=
      unistd_h.write
        (Interfaces.C.Int (pipe_fds (1)),
         signo_val'address,
         sys_types_h.Size_t (Interfaces.C.Int'size / 8));
  end clair_signal_handler;

  -- Implementation of the raise(3) wrapper
  procedure send (sig : Number) is
    result : constant Interfaces.C.Int := signal_h.c_raise (Interfaces.C.Int (sig));
  begin
    if result /= 0 then
      declare
        error_code : constant Interfaces.C.Int := Clair.Error.get_errno;
        error_msg  : constant String           :=
          "raise(3) failed: " &  "signal " & sig'image &
          " (errno: " & error_code'image & ")";
      begin
        case error_code is
          when errno_h.EINVAL => -- Invalid signal
            raise Clair.Error.Invalid_Argument with
                  "Invalid signal specified. " & error_msg;
          when errno_h.ESRCH => -- No such process
            raise Clair.Error.No_Such_Process with "Process not found. " &
                                                    error_msg;
          when errno_h.EPERM => -- Operation not permitted
            raise Clair.Error.Permission_Denied with "Permission denied. " &
                                                     error_msg;
          when others =>
            declare
              errno_text : constant String :=
                Clair.Error.get_error_message (error_code);
            begin
              raise Clair.Error.Unknown_Error with errno_text & ". " &
                                                   error_msg;
            end;
        end case;
      end;
    end if;
  end send;

  -- 수동 해시 함수 정의
  function hashfunc (key : Number) return Ada.Containers.Hash_Type is
  begin
    return Ada.Containers.Hash_Type (Interfaces.C.Int (key));
  end hashfunc;

  package Handler_Maps is new Ada.Containers.Hashed_Maps
    (key_type        => Number,
     element_type    => Handler_Access,
     hash            => hashfunc,
     equivalent_keys => "=");

  protected Handler_Registry is
    procedure r e g i s t e r (sig : in Number; handler : in Handler_Access);
    procedure call (sig : in Number);
  private
    handlers : Handler_Maps.Map;
  end Handler_Registry;

  protected body Handler_Registry is
    procedure r e g i s t e r (sig : in Number; handler : in Handler_Access) is
    begin
      if handler = null then
        handlers.delete (sig);
      else
        handlers.insert (sig, handler);
      end if;
    end r e g i s t e r;

    procedure call (sig : in Number) is
      -- 여기서 handler를 미리 선언할 필요가 없습니다.
    begin
      if handlers.contains (sig) then
        -- declare 블록을 사용해 지역 상수를 선언과 동시에 초기화합니다.
        declare
          handler : constant Handler_Access := handlers.element (sig);
        begin
          if handler /= null then
            handler.all (sig);
          end if;
        end;
      end if;
    end call;
  end Handler_Registry;

  -- Lifecycle management for automatic finalization
  type Finalizer is new Ada.Finalization.Limited_Controlled with null record;
  overriding
  procedure finalize (object : in out Finalizer);

  -- This object's declaration ensures finalize is called automatically
  finalizer_instance : Finalizer;

  overriding
  procedure finalize (object : in out Finalizer) is
    retval : Interfaces.C.Int;
  begin
    if pipe_fds (0) /= -1 then
      retval := unistd_h.close (Interfaces.C.Int (pipe_fds (0)));
    end if;
    if pipe_fds (1) /= -1 then
      retval := unistd_h.close (Interfaces.C.Int (pipe_fds (1)));
    end if;
    pragma unreferenced (retval);
  end finalize;

  function get_file_descriptor return Clair.File.Descriptor is
    (Clair.File.Descriptor (pipe_fds (0)));

  procedure set_action (sig : in Number; new_action : in Action) is
    sa     : aliased sys_signal_h.sigaction;
    retval : Interfaces.C.Int;
  begin
    retval := signal_h.sigemptyset (sa.sa_mask'access);

    if retval /= 0 then
      if retval = errno_h.EINVAL then
        raise Clair.Error.Invalid_Argument with "sigemptyset(3) failed";
      else
        declare
          error_code : constant Interfaces.C.Int := Clair.Error.get_errno;
          error_msg  : constant String           :=
            "sigemptyset(3) failed (errno: " & error_code'image & ")";
        begin
          raise Program_Error with "sigemptyset(3) failed";
        end;
      end if;
    end if;

    case new_action.kind is
      when Handle =>
        sa.sa_flags := Interfaces.C.Int (
           Interfaces.C.Unsigned (sys_signal_h.SA_RESTART) or
           Interfaces.C.Unsigned (sys_signal_h.SA_SIGINFO)
        );
        sa.uu_sigaction_u.uu_sa_sigaction := clair_signal_handler'access;
        Handler_Registry.r e g i s t e r (sig, new_action.handler);

      when Default =>
        sa.sa_flags := 0;
        sa.uu_sigaction_u.uu_sa_handler := Clair.Config.SIG_DFL;
        Handler_Registry.r e g i s t e r (sig, null);

      when Ignore =>
        sa.sa_flags := 0;
        sa.uu_sigaction_u.uu_sa_handler := Clair.Config.SIG_IGN;
        Handler_Registry.r e g i s t e r (sig, null);
    end case;

    if signal_h.sigaction2 (Interfaces.C.Int (sig), sa'access, null) /= 0
    then
      raise Program_Error with "sigaction system call failed";
    end if;
  end set_action;

  procedure dispatch is
    sig_num_c  : aliased Interfaces.C.Int;
    bytes_read : sys_types_h.ssize_t;
  begin
    loop
      bytes_read := unistd_h.read (Interfaces.C.Int (pipe_fds (0)),
                                   sig_num_c'address,
                                   Interfaces.C.Int'size / 8);
      if bytes_read > 0 then
        Handler_Registry.call (Number (sig_num_c));
      else
        -- 읽을 데이터가 없거나(EAGAIN 등) 에러 발생 시 루프 종료
        exit;
      end if;
    end loop;
  end dispatch;

begin
  if unistd_h.pipe (to_c_int_access (pipe_fds'address)) /= 0 then
    raise Program_Error with "pipe() creation failed during initialization";
  end if;
end Clair.Signal;

귀중한 시간 내어 읽어주셔서 감사하고, 어떤 피드백이든 환영입니다! 😊

추천 비추천

0

고정닉 0

0

댓글 영역

전체 댓글 0
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 제목 글쓴이 작성일 조회 추천
설문 반응이 재밌어서 자꾸만 놀리고 싶은 리액션 좋은 스타는? 운영자 25/07/28 - -
AD 휴대폰 액세서리 세일 중임! 운영자 25/07/28 - -
공지 프로그래밍 갤러리 이용 안내 [92] 운영자 20.09.28 45893 65
2876519 틱톡에 태이,우아 떡방박제됨 ㅋ 짤리기 전에 봐ㄱㄱ 프갤러(1.247) 19:12 6 0
2876516 체력 좀 더 키워야하는뎅 ♥불사신냥덩♥갤로그로 이동합니다. 19:05 9 0
2876514 나님 문화토양은 너무 다양해 ♥불사신냥덩♥갤로그로 이동합니다. 19:03 9 0
2876513 나님 왤케 특별할깡? ♥불사신냥덩♥갤로그로 이동합니다. 19:03 6 0
2876510 쭈쭈클럽❤+ ♥불사신냥덩♥갤로그로 이동합니다. 19:00 10 0
2876509 나님 피궁해서 애널 일찍 주무실게양⭐+ ♥불사신냥덩♥갤로그로 이동합니다. 18:58 7 0
2876508 틱톡에 태이,우아 떡방박제됨 ㅋ 짤리기 전에 봐ㄱㄱ 프갤러(1.247) 18:58 6 0
2876505 오늘 선풍기 바람으로 잠 설쳐서 수면부족 발명도둑잡기(118.216) 18:54 9 0
2876503 춍춍춍! 딱춍(61.253) 18:49 13 0
2876500 웹히키씨 죽은건 아니겠지? [2] 헬마스터갤로그로 이동합니다. 18:46 33 0
2876499 진보당도 예전에 당무회의 매번 유튜브에 중계했다 발명도둑잡기(118.216) 18:45 9 0
2876498 나도 한 시간 전쯤 집에서 부라보콘 먹었는데 발명도둑잡기(118.216) 18:43 9 0
2876497 이재명씨 국무회의 재밋더라 헬마스터갤로그로 이동합니다. 18:43 11 0
2876496 애널의달성 1.1/1/3 ♥불사신냥덩♥갤로그로 이동합니다. 18:43 16 0
2876495 김영광·채수빈, 넷플릭스 '나를 충전해줘' 출연 발명도둑잡기(118.216) 18:34 14 0
2876494 뿡야 했는데 조금 나온거 같당.. ♥불사신냥덩♥갤로그로 이동합니다. 18:24 14 0
2876493 끼힝끼히잉 딱쟁이(61.253) 18:23 22 0
2876492 아 씨발 ㅈ됐다ㅋㅋ 프갤러(211.202) 18:21 21 0
2876491 아이스크림 먹는 미소녀- 프갤러(121.172) 18:21 29 0
2876490 [대한민국][그라운드씨] 플라이츠 - JTBC 왜곡보도 반발 프갤러(121.172) 18:18 23 0
2876489 인내의 성적표가 처참하니 프갤러(220.84) 18:08 20 0
2876488 부모님께 8억을 증여받은 고등학생 발명도둑잡기(118.216) 18:07 15 0
2876487 대가리를 딱! 딱딱이(61.253) 18:06 22 0
2876486 폭염 폭우 현장 점검 발명도둑잡기(118.216) 18:03 11 0
2876485 [1] 프갤러(172.225) 17:58 18 0
2876484 [1] 딱코이(61.253) 17:56 25 0
2876483 가급적 서둘러 날을 잡아야 하는데 프갤러(220.84) 17:48 17 0
2876482 멍퀴님 성희롱 그만하세요 [2] ♥불사신냥덩♥갤로그로 이동합니다. 17:45 25 0
2876481 폭염 폭우 현장 점검 발명도둑잡기(118.216) 17:42 13 0
2876480 ㅋㅅㅋ ♥불사신냥덩♥갤로그로 이동합니다. 17:42 11 0
2876479 지금 한국은 무정부상태인둣;; ♥불사신냥덩♥갤로그로 이동합니다. 17:40 28 0
2876478 한국 관세 25%+a 대한민국 제 2의 IMF 부도시작 ♥불사신냥덩♥갤로그로 이동합니다. 17:39 21 1
2876476 저는 살면서 부산 대구를 가본 적이 없어요 [3] 아스카영원히사랑해갤로그로 이동합니다. 17:31 46 0
2876475 서울디지털단지 노동자는 바란다 “포괄임금 폐지해 주세요” 발명도둑잡기(118.216) 17:16 16 0
2876474 윤수괴가 안그랬다고 버티던 부하들 하나둘 분다는구나 [1] 헬마스터갤로그로 이동합니다. 17:12 28 0
2876473 일본무슨 1.5m 파도를 쓰나미라고 호들갑떨더라 [4] 헬마스터갤로그로 이동합니다. 16:46 49 0
2876471 포괄이 사라지면 굽삐는 어떻게 되는겁니까?! [4] 개멍청한유라갤로그로 이동합니다. 16:38 42 0
2876470 건강이 먼저다 [2] 개멍청한유라갤로그로 이동합니다. 16:35 40 0
2876468 복사 의뢰하러 데이터 복구센터 간다. 넥도리아(223.38) 16:33 13 0
2876467 [단독] 한국인 200명 넘게 당했다…캄보디아 창고서 무슨 일이 발명도둑잡기(118.216) 16:27 21 0
2876466 [샷!] 강남 한복판서 밥 퍼주는 편의점 발명도둑잡기(118.216) 16:22 16 0
2876465 웹앱땔깜을 비하하고싶어서 도저히 못참겠다 [1] 네오커헠(211.235) 16:15 67 0
2876464 섹. 프갤러(121.139) 16:06 21 0
2876463 노란봉투법 통과가 소비쿠폰보다 100배 행복하게 만들어준다 발명도둑잡기(118.216) 16:05 16 0
2876462 Rx Tx Engine - 작업 상황! [3] 프갤러(121.172) 16:01 51 0
2876461 Wow.. Postman mcp 라는 것도 있었네 어린이노무현갤로그로 이동합니다. 15:59 27 0
2876460 SUI 더블업 티셔츠 하나 사야겠당 어린이노무현갤로그로 이동합니다. 15:54 19 0
2876459 내년 나이 24살, 사회경험이 전혀 없습니다. 무스펙, 무경력 인생을 어 [1] ㅇㅇ(223.39) 15:49 47 0
2876458 나님 SoapUI로 json 쏘다 실패해서 [1] 아스카영원히사랑해갤로그로 이동합니다. 15:48 41 0
뉴스 ‘100인의 감정쇼: 더 시그니처’ 박찬호 소장품 3종, 국민 감정가 16억…”예상보다 높게 커리어 인정해 줘 감사” 디시트렌드 18:00
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2