2012. 7. 13. 16:33

파이프는 프로세스가 종료되면 사라져 영구적이지 못하다는 문제점이 있다.

이런 문제점을 해결한 것이 FIFO(이름있는 파이프, 'named pipes'라고함)

FIFO에는 이름이 부여되므로 부모 자식 관계가 아닌 프로세스에서도 파이프 이름만 알면 이용가능하고

삭제하지 않는한 영구히 존재

a.out
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define SIZE 128   /* buffer 크기를 나타내는 매크로 */
#define FIFO "fifo"   /* fifo를 나타내는 매크로 */

main(int argc, char *argv[])
{
    int fd;
    char buffer[SIZE];

    /* 접근 권한이 0666인 fifo라는 이름의 FIFO 생성 */
    if(mkfifo(FIFO, 0666) == -1) {
       perror("mkfifo failed");
       exit(1);
    }
    /* FIFO를 사용하기 위해서는 열어야 함 */
    /* FIFO를 이용한 읽기 전용 프로세스와 쓰기 전용 프로세스가 실행되면 쓰기 전용 프로세스가 FIFO에 데이터를 쓸때 까지 읽기 전용 프로세스는 기다린다. 그러므로 FIFO에 데이터가 쓰여져야 read 호출이 동작한다. 이때 스기 전용 프로세스가 종료되어 FIFO에 데이터를 쓸 프로세스가 없는 상황에서 읽기 전용 프로세스가 read 호출을 하면 바로 0을 반환한다. 결국 불필요한 반복 실행을 하게 된다. 그러나 rw로 설정하면 쓰기 전용 프로세스가 종료하더라도 FIFO에 데이터를 쓸 프로세스가 있다고 인식하므로 read호출은 FIFO에 데이터가 전달될 때 까지는 기다리게 되어 불필요한 반복을 을 하지 않게 된다. */
    if((fd=open(FIFO, O_RDWR)) == -1) {
       perror("open failed");
       exit(1);
    }

    /* 무한 반복 */
    while(1) {
       /* fifo로부터 읽기 */
       if(read(fd, buffer, SIZE) == -1) {
          perror("read failed");
          exit(1);
       }
       /* 읽은 데이터가 quit이면 종료 */
       if(!strcmp(buffer, "quit"))
          exit(0);
       /* 읽은 데이터를 출력 */
       printf("receive message: %s\n", buffer);
    }
}


b.out
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define SIZE 128   /* buffer 크기를 나타내는 매크로 */
#define FIFO "fifo"   /* fifo를 나타내는 매크로 */

main(int argc, char *argv[])
{
    int fd,i;
    char buffer[SIZE];

    /*fifo 열기*/
    if((fd=open(FIFO,O_WRONLY)) == -1) {
        perror("open failed");
        exit(1);
    }

    /*명령라인 두 번째 인수부터 마지막 인수까지*/
    for(i=1 ; i<argc ; i++) {
        strcpy(buffer, argv[i]);
        /*fifo에 쓰기 */
        if(write(fd,buffer,SIZE) == -1) {
            perror("write failed");
            exit(1);
        }
    }
    exit(0);
}

[localhost@local]#a.out &
[localhost@local]#b.out 'C programming Linux'
receive message : C programming
receive message : Linux

[localhost@local]#b.out quit
[1]+ Done a.out

Posted by 몰라욧