프로세스 사이의 통신 - 파이프

이동욱

2021/08/14

Categories: 네트워크

파이프


#include <unistd.h>

int pipe(int pipefd[2]);

예제

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

void error_proc(const char *);

int main(int argc, char *argv[]) {
  int pipe_fd[2];
  int res;
  char buff[BUFSIZ];
  pid_t pid;
  int read_len, n_write;
  int open_fd, status;

  if (argc != 2) {
    fprintf(stderr, "usage: %s [file] \n", argv[0]);
  }

  res = pipe(pipe_fd);
  if (res == -1) error_proc("pipe");

  pid = fork();
  
  if (pid == -1) error_proc("fork");
  if (pid == 0) { // child
    close(pipe_fd[1]);
    open_fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC);
    while (1) {
      read_len = read(pipe_fd[0], buff, BUFSIZ - 1);
      if (read_len == -1) error_proc("read");
      if (read_len == 0) break;
      write(open_fd, buff, read_len);
    }
    printf("parent process closed the pipe. \n");
    close(open_fd);
    close(pipe_fd[0]);
    return 0;
  } else { // parent
    close(pipe_fd[0]);
    while (1) {
      fgets(buff, BUFSIZ - 1, stdin);
      read_len = strlen(buff);
      if (read_len == 4 && !strncmp(buff, "END", 3))
        break;
      n_write = write(pipe_fd[1], buff, read_len);
      if (n_write == -1) error_proc("write");
      printf("%d bytes are written \n", n_write);
    }
    close(pipe_fd[1]);
    wait(&status);
    return 0;
  }
}

void error_proc(const char *str) {
  fprintf(stderr, "%s: %s\n", str, strerror(errno));
  exit(1);
}

참고 문헌


>> Home