파이프(Pipe)

파이프(Pipe)는 프로세스 간 통신(IPC)의 한 방법으로, 단방향 데이터 흐름을 제공하는 가장 오래된 IPC(프로세스 간 통신) 메커니즘 중 하나이다. 파이프는 한쪽 끝에서 데이터를 쓰고 다른 쪽 끝에서 데이터를 읽을 수 있게 해준다.

종류

  1. 익명 파이프 (Anonymous Pipe): 부모-자식 프로세스 간 통신에 사용

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    import os
    
    def create_anonymous_pipe():
        """익명 파이프 생성 예제"""
        read_fd, write_fd = os.pipe()
    
        pid = os.fork()  # 프로세스 생성
    
        if pid > 0:  # 부모 프로세스
            os.close(read_fd)  # 읽기 끝 닫기
            os.write(write_fd, "Hello from parent".encode())
            os.close(write_fd)
        else:  # 자식 프로세스
            os.close(write_fd)  # 쓰기 끝 닫기
            message = os.read(read_fd, 1024).decode()
            print(f"Child received: {message}")
            os.close(read_fd)
    
  2. 이름 있는 파이프 (Named Pipe 또는 FIFO): 관련 없는 프로세스 간 통신에 사용

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    import os
    
    def create_named_pipe():
        """이름 있는 파이프 생성 예제"""
        pipe_path = "/tmp/my_pipe"
    
        # 파이프 생성
        if not os.path.exists(pipe_path):
            os.mkfifo(pipe_path)
    
        # 파이프 사용
        with open(pipe_path, 'w') as pipe_write:
            pipe_write.write("Hello through named pipe")
    

파이프의 구현과 사용

기본적인 파이프 통신 구현:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import os
import sys

class PipeCommunication:
    def __init__(self):
        self.read_fd, self.write_fd = os.pipe()
        
    def parent_process(self, message):
        """부모 프로세스의 파이프 사용"""
        os.close(self.read_fd)  # 읽기 끝 닫기
        
        try:
            os.write(self.write_fd, message.encode())
        finally:
            os.close(self.write_fd)
            
    def child_process(self):
        """자식 프로세스의 파이프 사용"""
        os.close(self.write_fd)  # 쓰기 끝 닫기
        
        try:
            message = os.read(self.read_fd, 1024).decode()
            return message
        finally:
            os.close(self.read_fd)

특징

  • 단방향 통신(Half-Duplex)
  • 양방향 통신을 위해서는 두 개의 파이프가 필요
  • 커널 영역에서 관리되는 버퍼를 통해 데이터 전송

구현

  • Unix/Linux에서 pipe() 시스템 콜을 사용하여 생성
  • 파일 디스크립터를 통해 접근 (읽기용, 쓰기용)

장점

  • 간단한 구현
  • 동기화 문제 해결 (커널에서 관리)

제한사항

  • 익명 파이프는 관련 프로세스 간에만 사용 가능
  • 네트워크를 통한 통신 불가 (동일 시스템 내에서만 사용)

참고 및 출처