coding/운영체제

운영체제 Linux 파이프 통신

codingdoeun 2021. 12. 5. 14:41

IPC 구현방법에는 3가지가 있다.

  • Unnamed pipe : 부모 자식 프로세스들간의 통신에 사용한다.
  • Named pipe : 상관관계 없는 프로세스들간의 통신에 사용한다.
  • Socket : 다른 컴퓨터상에서 동작하는 프로세스들간의 통신에 사용한다.

단방향 통신에는 파이프를 1개만 사용하며, 양방향 통신을 위해서는 2개의 파이프를 사용해야한다.

FIFO를 지원하는 특수 파일로 mkfifo명령어를 사용하여 생성한다.

 

 

pipe 기반의 생산자 프로그램 코드

#include<stdio.h>
#include<fcntl.h>

int main(void) {
    int fd, n_write, i;

    mkfifo("/tmp/my_pipe", 0644);

    if ((fd = open("/tmp/my_pipe", 0_WRONLY, 0644)) == -1)
    {
        printf("Pipe Open Error \n"); 
        return -1;
    }

    for (i = 0; i < 10; i++)
    {
        if ((n_write = write(fd, &i, sizeof(i))) == -1)
        {
            printf("Write Error\n");
            return -1;
        }
        printf("Producer Sent: %d \n", i);
        sleep(1);
    }
    close(fd);
    return 0;
}

 

 

소비자 프로그램 코드 

#include<stdio.h>
#include<fcntl.h>

int main(void) {
    int fd, n_read=0, i;
    int msg;

    mkfifo("/tmp/my_pipe", 0644);

    if ((fd = open("/tmp/my_pipe", 0_RDONLY, 0644)) == -1)
    {
        printf("Pipe Open Error \n"); 
        return -1;
    }

    for (i = 0; i < 10; i++)
    {
        if ((n_read = read(fd, &msg, sizeof(i))) == -1)
        {
            printf("Write Error\n");
            return -1;
        }
        printf("Producer Sent: %d \n", msg);
        sleep(2);
    }
    close(fd);
    return 0;
}

 

실행결과

Producer Sent : 0

Consumer Received : 0

Producer Sent : 1

Consumer Received : 1

Producer Sent : 2

Producer Sent : 3

Consumer Received : 2

Producer Sent : 4

Producer Sent : 5

Consumer Received : 3

Producer Sent : 6

Producer Sent : 7

Consumer Received : 4

Producer Sent : 8

Producer Sent : 9

Consumer Received : 5

Consumer Received : 6

Consumer Received : 7

Consumer Received : 8

Consumer Received : 9

 

'coding > 운영체제' 카테고리의 다른 글

운영체제 개념 및 OS 설치하기  (0) 2021.11.13