디시인사이드 갤러리

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

갤러리 본문 영역

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

나르시갤로그로 이동합니다. 2025.07.24 09:15:29
조회 70 추천 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 - -
2876079 장기간 유지되던 경쟁관계의 순위가 바뀌는 시기나 분위기, 계기 특징 발명도둑잡기(118.216) 07.29 100 0
2876078 인간을 생체 대이터센터로 만드는 기술 개발즁⭐ ♥불사신냥덩♥갤로그로 이동합니다. 07.29 32 0
2876077 418번길 [1] 넥도리아(223.38) 07.29 36 0
2876076 대공황 ♥불사신냥덩♥갤로그로 이동합니다. 07.29 31 0
2876075 김건모-내가 그댈 느끼는 만큼 발명도둑잡기(118.216) 07.29 18 0
2876074 소비쿠폰을 돈으로 만드는 법 발명도둑잡기(118.216) 07.29 71 0
2876073 ai때문에 현타와서 코딩 놓은지 좀 됐는데 [1] ㅇㅇ(118.235) 07.29 121 0
2876072 늑대와 개 유전자 갯수 차이 교배 방법 발명도둑잡기(118.216) 07.29 23 0
2876071 데이터복구 IMMOU 넥도리아(223.38) 07.29 30 0
2876070 소비쿠폰=로또 4등 세번 당첨 발명도둑잡기(118.216) 07.29 24 0
2876069 연봉 1억 넘으면 배급권은 나눔해야지 ㅇㅇ(49.165) 07.29 32 0
2876068 련봉1억따리가 이런거 살수 있슴? ㅇㅇ(223.38) 07.29 47 0
2876067 생물학에서 변종이 원래의 종을 역전하는 경우 연구 발명도둑잡기(118.216) 07.29 40 0
2876066 병렬프로그래밍도 좀 공부하고 그래라 프갤러(122.43) 07.29 57 0
2876065 다리 찢기 발명도둑잡기(118.216) 07.29 28 1
2876064 오늘의 발명 실마리: 에어콘 쏘이는 영역 줄이는 실내용 텐트 발명도둑잡기(118.216) 07.29 27 0
2876063 소비쿠폰 149400원을 어디에 쓸 것인가 [1] 발명도둑잡기(118.216) 07.29 41 0
2876062 AI시대에 숫자 3개 정렬한다고 꼬박 5시간 고민하는게 맞는거냐?? [1] ㅇㅇ(223.38) 07.29 58 0
2876061 본인 AI구독 ㅁㅌㅊ? 일이삼123갤로그로 이동합니다. 07.29 62 0
2876060 개쩌는 서비스 아이디어 떠올랐다. 뭐냐면 [5] ㅇㅇ(211.235) 07.29 77 0
2876058 이.. 이대로 가면.. ♥불사신냥덩♥갤로그로 이동합니다. 07.29 49 0
2876056 4mat - paper dolls 배구공(119.202) 07.29 36 0
2876054 외국인 보험비 유출 < 주한미군 방위비 일본, 괌, 하와이 유출 발명도둑잡기(118.216) 07.29 24 0
2876053 민주 정일영, 수해 복구라며 '고향집 밭' 정비? 발명도둑잡기(118.216) 07.29 39 0
2876052 냥덩이 무좀 걸릴 예정 발명도둑잡기(118.216) 07.29 32 0
2876051 나님 혹시?! 프로그래밍 천재?!?!?!!! [1] ㅇㅇ(223.38) 07.29 88 0
2876050 ❤✨☀⭐⚡☘⛩나님 시작합니당⛩☘⚡⭐☀✨❤ ♥불사신냥덩♥갤로그로 이동합니다. 07.29 31 0
2876049 MS Word 문서에 숨겨져 저장되는 주요 정보 발명도둑잡기(118.216) 07.29 31 0
2876045 본인 운동화 6켤레 [1] 아스카영원히사랑해갤로그로 이동합니다. 07.29 54 0
2876044 2찢명 광우병은 착한광우병? ♥불사신냥덩♥갤로그로 이동합니다. 07.29 54 0
2876043 이혜성 해사 발명도둑잡기(118.216) 07.29 25 0
2876042 코린이 자바배우고있는데 [2] 프갤러(112.222) 07.29 72 0
2876041 나이키 운동화는 웰케 비싸나요 [1] 아스카영원히사랑해갤로그로 이동합니다. 07.29 52 0
2876040 요즘 제로콜라 안마심 [2] 프갤러(113.59) 07.29 58 0
2876039 컴파일러 과목 들을까? [1] 프갤러(118.235) 07.29 63 0
2876038 재벌 대기업 it 계열사 vs 토스 당근 오늘의 집 프갤러(110.13) 07.29 31 0
2876037 저연봉 개발자들아 제발 정신 차려라 프갤러(121.145) 07.29 59 0
2876036 우주에 중심은 있당⭐+ ♥불사신냥덩♥갤로그로 이동합니다. 07.29 59 0
2876035 갑자기 이준석은 왜 [2] 아스카영원히사랑해갤로그로 이동합니다. 07.29 85 0
2876034 워드안쓰고 hwp 쓰는놈들 줘패고싶네 [1] 뉴진파갤로그로 이동합니다. 07.29 62 0
2876033 러 군 ‘투명 망토’ 알고 보니 위험에 더 노출 발명도둑잡기(118.216) 07.29 39 0
2876028 중소기업 장시간 근무 줄었지만‥유연근로는 대기업의 3분의 1 발명도둑잡기(118.216) 07.29 28 0
2876025 이 옷 한번 입었다가… 윤리위서 3년 조사받은 美 의원 발명도둑잡기(118.216) 07.29 41 0
2876021 오세훈, ‘효과성 논란’ 손목닥터 9988에 313억 추경 발명도둑잡기(118.216) 07.29 45 0
2876020 냥덩이에게 잘해줘야하는 진짜 이유⭐+ ♥불사신냥덩♥갤로그로 이동합니다. 07.29 43 0
2876019 파출소 자원하는 경찰대 출신들...알고보니 ‘로스쿨 열공 중’ 발명도둑잡기(118.216) 07.29 58 0
2876018 극좌구라당 근황 ㄹㅇ..;; ♥불사신냥덩♥갤로그로 이동합니다. 07.29 52 0
2876014 어제 제미나이씨로부터 제너레이터 js에 대해 배웟습니다 [3] 헬마스터갤로그로 이동합니다. 07.29 102 0
2876013 라이엇채용공고 [1] 프갤러(106.101) 07.29 74 0
2876012 챗봇 api한방에 100원? 헬마스터갤로그로 이동합니다. 07.29 101 0
뉴스 이은지 맞아? “살이 너무 많이 빠졌다” 걸그룹 몸매 변신 디시트렌드 07.30
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2