pipe()

- 하나의 파이프 및 파이프에 대한 두 개의 파일 디스크립터가 생성

- 하나의 파이프를 프로세스들이 공유

#include "sys/types.h"
#include 
#include 
#include 
#include 

#define MAXLINE 4096 /* max line length */ 

/* err_sys("") --> return(1) */

int main(void)
{
    int n, fd[2];
    pid_t pid;
    char line[MAXLINE];

    if (pipe(fd) < 0) {
        printf("pipe error \n");
        return(-1);
        /* err_sys("pipe error"); */
    }

    if ( (pid = fork()) < 0) {
        printf("fork error \n");
        return(-2);
        /* err_sys("fork error"); */

    } else if (pid > 0) { /* parent */

        close(fd[0]);
        write(fd[1], "Hello world\n", 12);

    } else { /* child */
        close(fd[1]);
        n = read(fd[0], line, MAXLINE);
        write(STDOUT_FILENO, line, n);
    }

    return(0);
}
/* The end of function */

=============================================================

파이브열고

포크로 자식 프로세스 만들어다가

read시키는데

이떄, 부모프로세스는 write으로 파이프의 내용을 읽어온다.

결국 위의 코드의 결과는

printf("%s\n", "Hello world");

와 동일하게 나옴. write함수에서 fd들어갈곳에 STDOUT_FILENO플래그를

넣었으니깐.

=============================================================

pipe() 함수는 파일 디스크립터 쌍을 생성하네, 2개 생성하는데.

filedes[2] => filedes[0] Read, filedes[1] Write. 용도로 만든다.

사용법
#include <unistd.h>

int pipe(int filedes[2]);

=============================================================

fork()함수는 Child process 생성하는 기본적인 멀티 프로세싱 함수

사용법
#include <unistd.h>

pid_t fork(void);

=============================================================

close()함수는 pipe로 열린 descriptor 닫아버리는 함수

SYNOPSIS
#include <unistd.h>

int close(int fd);

=============================================================


출처

1. advanced programming in the unix environment

 2. http://gatolu.tistory.com/entry/%ED%8C%8C%EC%9D%B4%ED%94%84-%ED%95%A8%EC%88%98 

반응형

+ Recent posts