디시인사이드 갤러리

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

갤러리 본문 영역

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

나르시갤로그로 이동합니다. 2025.07.24 09:15:29
조회 73 추천 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 45991 65
2877499 avif는 왜캐 지원이 느린지 밀우갤로그로 이동합니다. 02:04 7 0
2877498 위키드-내가 바라는 세상 발명도둑잡기(118.216) 01:35 7 0
2877497 놀러가서 피부 타고 뜨거울때 직빵인거 싱글벙글(222.105) 01:30 7 0
2877496 미국에서 ai 천재 2400억 주고 데려오네 프갤러(221.146) 01:21 17 0
2877495 [사이언스프리즘] ‘나만 살자’는 뇌 구조 바꿔야 정치가 산다 발명도둑잡기(118.216) 01:21 7 0
2877494 여러 생각으로 머리가 아파서 [2] 아스카영원히사랑해갤로그로 이동합니다. 00:52 33 0
2877493 흠.. 공감이란게 가능한가? [1] ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 00:49 17 0
2877492 MCP 만드는법 모르는 호구 없제 프갤러(121.133) 00:33 17 0
2877491 놀러가서 피부 타고 뜨거울때 직빵인거 싱글벙글(222.105) 00:32 10 0
2877490 소개팅 실패 사례.jpg [1] 발명도둑잡기(118.216) 00:28 19 0
2877489 ai 20%정도 부족한거 언제쯤 고쳐지려나 [1] 뉴진파갤로그로 이동합니다. 00:06 23 0
2877488 유튜브프리미엄페루가격 진짜 이 가격 맞음? 프갤러(125.243) 00:03 30 0
2877487 나님이 “냥덩“입니당❤+ ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 00:01 19 0
2877486 정청래, 민주당 대표 당선 발명도둑잡기(118.216) 08.02 11 0
2877485 이게 2003년 작품이었넹 ㄷㅅㄷ ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 22 0
2877484 놀러가서 피부 타고 뜨거울때 직빵인거 싱글벙글(222.105) 08.02 17 0
2877483 비전공 국비출신 일본 한국계 좆소 취업자는 이력서 어떻게 씀? 프갤러(125.181) 08.02 33 0
2877482 [벌거벗은세계사] '에디슨'이 전기 사업 때문에 동물을 죽였다? 발명도둑잡기(118.216) 08.02 16 0
2877481 나님은 오타쿠가 이님 ㅇㅅㅇ ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 21 0
2877480 충격.. ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 23 0
2877478 할까 ㅇㅅㅇ [4] 어린이노무현갤로그로 이동합니다. 08.02 51 0
2877475 이재명씨 리더십론 알찬것같구나 [4] 헬마스터갤로그로 이동합니다. 08.02 49 0
2877473 격충.. ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 21 0
2877472 러스트가 그렇게 좋으면 나처럼 책을 쓰던가 ㅋㅋ [4] 나르시갤로그로 이동합니다. 08.02 40 0
2877471 짱깨 또 질병 퍼트리는즁 ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 15 0
2877470 근로소득으로만 4억 (회사주식포함) [1] ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 37 0
2877469 우파도 개미아니누 뒷통수한방(1.213) 08.02 14 0
2877468 좌파는 개미다 ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 25 0
2877467 쪽잠자고 공부하니까 [2] 루도그담당(58.239) 08.02 32 0
2877466 나님 주무시기전 소통⭐+ 질문 받음 ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 26 0
2877464 악조건에 갈려 죽으라는것이 신 개새끼의 뜻이겠죠. 프갤러(220.84) 08.02 19 0
2877462 여름의 한국은 거대한 돌침대당⭐+⭐+⭐+⭐+⭐+ By 나님 ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 12 0
2877461 내일 짬뽕안먹으면 뒤질듯 프갤러(113.59) 08.02 15 0
2877460 안식을 내어놓아라 아니면 프갤러(220.84) 08.02 13 0
2877459 내 꿈은 일본 서브컬쳐로 무언가 저지르는 것이기 때문에 아스카영원히사랑해갤로그로 이동합니다. 08.02 16 0
2877458 나님 게임 좀 하다 주무실게양 ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 18 0
2877457 김하온 (HAON) - 피가 모자라 발명도둑잡기(118.216) 08.02 13 0
2877456 정청래는 왜 미국 대사관에 도시락 폭탄 던짐? [4] 아스카영원히사랑해갤로그로 이동합니다. 08.02 40 0
2877455 KPOPPED — Official Trailer | Apple TV+ 발명도둑잡기(118.216) 08.02 17 0
2877454 뛰뛰에서 가장 중요한건 온도와 습도 ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 18 0
2877453 솔루션회사에서 일본 서비스회사로 전직하는 건 [13] 아스카영원히사랑해갤로그로 이동합니다. 08.02 58 0
2877452 졸려씨박 [1] 프갤러(223.38) 08.02 16 0
2877451 요즘 컴퓨터 근황 입니다. [5] 넥도리아(220.74) 08.02 56 0
2877450 보석놈 러스트 코드가 보고 싶나? 프갤러(14.58) 08.02 18 0
2877449 ㅠ ㅅ ㅠ.. ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 11 0
2877448 디씨가 나한테 끼친 영향 슈퍼막코더(126.194) 08.02 25 0
2877446 ⭐+ [1] ♥님아그다리를건너지마오쩌둥♥갤로그로 이동합니다. 08.02 23 0
2877445 [사설]13년 만에 FTA 사실상 폐기 발명도둑잡기(118.216) 08.02 32 0
2877444 모든게 원망스럽다 ㅇㅇ(118.235) 08.02 22 0
뉴스 걸그룹 전 멤버, ‘술집서 일하다 남편 만나’ 악성 루머 유포자 고소 디시트렌드 08.01
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2