디시인사이드 갤러리

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

갤러리 본문 영역

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

나르시갤로그로 이동합니다. 2025.07.24 09:15:29
조회 63 추천 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 - -
2874573 커서 200불짜리 질렀는데 하루만에 경고 날라왔다 [1] 프갤러(1.249) 07.25 50 0
2874572 김성수 장대호는 전생에 뭔지랄을했길래 좇센에서 태어났을까 뒷통수한방(1.213) 07.25 31 0
2874571 원피스 판타지를 능가하는 현실 최고의 선장은 발명도둑잡기(118.216) 07.25 29 0
2874569 음악 장르 다양성 연구 발명도둑잡기(118.216) 07.25 29 0
2874568 제미나이 프로 4개월 할인권 ㅇㅇ(211.236) 07.25 43 0
2874567 로자룩셈부르크 갤러리 글 발명도둑잡기(118.216) 07.25 39 0
2874565 윤석열 각하도 전국민 민생회복지원금 지원 중 발명도둑잡기(118.216) 07.25 51 0
2874564 오 이거 뭐지 3일 전에 산건대 15배오름 [2] 어린이노무현갤로그로 이동합니다. 07.25 64 0
2874560 왔따! 인간남녀! ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 40 0
2874559 공수처 검찰청 경찰청 국제수사 과학수사 포랜식수사 기무사 국정원 존재이유 뒷통수한방(1.213) 07.25 32 0
2874556 우리 농산어촌은 동학운동 하듯이 지켜야 한다 발명도둑잡기(118.216) 07.25 28 0
2874554 재명지원금땜에 돼지되게 생겻다 [3] 헬마스터갤로그로 이동합니다. 07.25 52 0
2874553 ㄳㄷㄷㄷㄷㄷㄷㄷㄷㄷㄷㄷㄷ 프갤러(61.73) 07.25 65 0
2874551 AI 로 모든 직업이 사라질거야 [1] ㅇㅇ(183.101) 07.25 64 0
2874549 2/1 ㅌㅊ 시도 해봐야징 ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 39 0
2874547 흠.. 2.3ㅌㅊ.. ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 27 0
2874545 성북길빛도서관에서 한 시간 쉬다 간다 발명도둑잡기(39.7) 07.25 39 0
2874542 알리익스프레스 정지된거 너무 불편하다 [2] 발명도둑잡기(211.234) 07.25 47 0
2874541 와 나님 갑자기 폭똥 터져서 큰일날뻔;; ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 37 0
2874540 ... 프갤러(118.37) 07.25 42 0
2874539 스프링 드라마 발명도둑잡기(211.234) 07.25 53 0
2874538 양산형 도배기 이거써라 ㅋㅋㅋ 프갤러(118.37) 07.25 40 0
2874536 "프로그래밍은 엉덩이로 한다" 발명도둑잡기(211.234) 07.25 38 0
2874535 도배기나역류기가 막혔다는 병신은 엠창새끼임? [3] 프갤러(118.37) 07.25 70 0
2874534 나는조현병이야 나는내향적이야 손발이시립디다갤로그로 이동합니다. 07.25 37 0
2874533 윤석열 계엄 손해배상 인정…‘1만명 위자료 소송’ 이어진다 발명도둑잡기(211.234) 07.25 54 0
2874532 공수처 검찰청 경찰청 국제수사 과학수사 포랜식수사 기무사 국정원 존재이유 뒷통수한방(1.213) 07.25 25 0
2874531 외교참사 국제왕따 2찢명 회생방안 ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 31 0
2874530 106.101 심리공작원 글 발명도둑잡기(118.235) 07.25 36 1
2874528 박보영 엘르 화보 발명도둑잡기(118.235) 07.25 55 0
2874526 이바닥이 이렇게까지 폐쇄적인줄 몰랐음 프갤러(118.235) 07.25 49 0
2874525 성냥사세양..성냥사세양.. 성냥말구 다른것두 팔아양.. ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 39 0
2874524 뉴프로 개새끼야!!!!!!!!!!!!!!!!!!!! [1] 아스카영원히사랑해갤로그로 이동합니다. 07.25 64 0
2874523 흑녀 생머리 존꼴 ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 58 0
2874522 개젗센 연도별 200충개돼지노예 신입 요구사항 뒷통수한방(1.213) 07.25 41 0
2874521 영화 <터미네이터> 시리즈가 뻥인 이유 [1] 발명도둑잡기(182.222) 07.25 41 0
2874520 프로그래밍 같은 지식에만 심취하면 [11] 아스카영원히사랑해갤로그로 이동합니다. 07.25 120 0
2874519 개발자는 영어잘하면 해외취업 쉬워? [1] 프갤러(118.235) 07.25 61 0
2874518 요즘 왜 다 런닝화같은 비새는 신발뿐? 헬마스터갤로그로 이동합니다. 07.25 40 0
2874517 핵전쟁 나면 우선 it산업은 개박살이고 뭘 준비해할까? ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 34 0
2874516 첫 출근 뭐해야하노 [1] 세상아덤벼라갤로그로 이동합니다. 07.25 49 0
2874515 원종이가 꿈꾸던 스카이넷 가동 도입중.. [2] ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 56 0
2874514 ai 가 인류를 위협한다는 시나리오 봐라 프갤러(183.101) 07.25 40 0
2874513 핵전쟁 3차세계대전 임박(미-러 핵무기제한 협정 내년 2월 종료) ♥팬티스타킹냥덩♥갤로그로 이동합니다. 07.25 67 0
2874512 종교가 없어져도 종교 대체물은 나오기 마련임 [3] 아스카영원히사랑해갤로그로 이동합니다. 07.25 87 0
2874511 어떤 프로그래밍 방법도, 프로그래밍 모델도 반드시 새는 부분이 존재함 ㅆㅇㅆ(124.216) 07.25 42 0
2874509 내가 좋아하는 프로그래밍 명언 중에 이런 말이 있다. [1] ㅆㅇㅆ(124.216) 07.25 73 0
2874508 종교 = 사람이 어떻게 살아야하는가 부드러운곰탱이갤로그로 이동합니다. 07.25 44 1
2874507 코딩을 좋아하긴 했지 [4] 프갤러(106.101) 07.25 103 2
2874506 븅신들아 프갤러(211.36) 07.25 45 0
뉴스 차은우 맞아? 군대 가기 전 ‘완전 삭발’…“신기하고 어색” 디시트렌드 07.28
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

뉴스

디시미디어

디시이슈

1/2