Linux IPC - PIPE


1. Create PIPE

    int handle[2];
    int ret;  

    ret = pipe(handle); /*handle[0] : read descriptor, handle[1]: write descriptor*/

    if (ret < 0)
    {
       fprintf(stderr, "pipe error");
    }

2. Set PIPE (optional)
   
    to change the default behavior from blocking mode to non-blocking mode

    #include <fcntl.h>

    if (fcntl (handle[0], F_SETFL, O_NDELAY) < 0)
    {
        fprintf(stderr, "fcntl error");
    }

2. Read/Write PIPE

    nread = read(handle[0], buf, MAXSIZE));

    write (handle[1], buf, MAXSIZE);

3. Close PIPE
   
    close (handle[0]);
    close (handle[1]);

4. Example:

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

#define MSGSIZE 16

/*------ Function prototypes ----------*/
void parent (int p[]);
void child (int p[]);
void fatal (char *);

/*------- Message Strings -------------*/
char *msg1 = "Hello World";
char *msg2 = "Goodbye World";

int main (void)
{
  int pfd[2];

  /*----- Open the pipe -----------*/
  if (pipe(pfd) < 0)
  {
    fatal ("pipe call");
    exit(1);
  }

  /*---- Set the O_NDELAY flag for p[0] -----------*/
  if (fcntl (pfd[0], F_SETFL, O_NDELAY) < 0)
      fatal ("fcntl call");

  /*-------- fork ---------------*/

  switch(fork())
  {
    case -1:        /* error */
    fatal ("fork call");
    case 0:        /* It's the child */
      child (pfd);
    default:       /* parent */
      parent (pfd);
  }
}

/*------- Parent Code -------*/
void parent (int p[2])
{
  int nread;
  char buf[MSGSIZE];

  close (p[1]);    /* close the write descriptor */

  for (;;)
  {
    switch (nread = read(p[0], buf, MSGSIZE))
    {
      case -1:
      case 0:
    printf ("(pipe empty)/n");
    sleep(1);
      break;
    default:
      if (strcmp (buf, msg2) == 0)
      {
      printf ("End of Conversation/n");
      exit(0);
      }
      else
    printf ("MSG = %s/n", buf);
    }
  }
}

/*------ Child Code --------------------*/
void child (int p[2])
{
  int count;

  close (p[0]);    /* close the read descriptor */

  for (count = 0; count < 3; count ++)
  {
    write (p[1], msg1, MSGSIZE);
    sleep (3);
  }
  /*--- Send final message ------------*/
  write (p[1], msg2, MSGSIZE);
  exit(0);
}

/*---------- Error function ------*/
void fatal (char *s)
{
  perror (s);    /* print error msg and die */
  exit(1);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值