Demo entry 6623824

c

   

Submitted by anonymous on Jun 10, 2017 at 07:57
Language: C. Code size: 1.8 kB.

#include <sys/types.h>
#include <sys/file.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char r_buf[4];  //读缓冲
char w_buf[4];  //写缓冲
int pipe_fd[2];
pid_t pid1, pid2, pid3, pid4;
int producer(int id);
int consumer(int id);
int main(int argc, char **argv)
{
  if (pipe(pipe_fd) < 0)
    {
      printf("pipe create error \n");
      exit(-1);
    }
  else
    {
      printf("pipe is created successfully!\n");
      if ((pid1 = fork()) == 0)
        producer(1);
      if ((pid2 = fork()) == 0)
        producer(2);
      if ((pid3 = fork()) == 0)
        consumer(1);
      if ((pid4 = fork()) == 0)
        consumer(2);
    }
  close(pipe_fd[0]);    //需要加上这两句
  close(pipe_fd[1]); //否这会有读者或者写者永远等待
  int i, pid, status;
  for (i = 0; i < 4; i++)
    pid = wait(&status);
  exit(0);
}
int producer(int id)
{
  printf("producer %d is running!\n", id);
  close(pipe_fd[0]);
  int i = 0;
  for (i = 1; i < 10; i++)
    {
      sleep(3);
      if (id == 1)    //生产者1
        strcpy(w_buf, "aaa\0");
      else    //生产者2
        strcpy(w_buf, "bbb\0");
      if (write(pipe_fd[1], w_buf, 4) == -1)
        printf("write to pipe error\n");
    }
  close(pipe_fd[1]);
  printf("producer %d is over!\n", id);
  exit(id);
}
int consumer(int id)
{
  close(pipe_fd[1]);
  printf("consumer %d is running!\n", id);
  if (id == 1)  //消费者1
    strcpy(w_buf, "ccc\0");
  else    //消费者2
    strcpy(w_buf, "ddd\0");
  while (1)
    {
      sleep(1);
      strcpy(r_buf, "eee\0");
      if (read(pipe_fd[0], r_buf, 4) == 0)
        break;
      printf("consumer %d get %s, while the w_buf is %s\n", id, r_buf, w_buf);
    }
  close(pipe_fd[0]);
  printf("consumer %d is over!\n", id);
  exit(id);
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).