linux 管道(进程间通信)

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

#define MAXSIZE 80

int main (int argc, char *argv[])
{
	int fd[2];
	pid_t pid;
	char line[MAXSIZE];
	int n;

	if (pipe(fd) < 0)
	{
		perror("pipe error!");
		exit(1);
	}

	if((pid = fork()) < 0)
	{
		perror("fork error!");
		exit(1);
	}

	else if(pid > 0)
	{
		close(fd[0]);
		write(fd[1], "hello world\n", 12);
		wait(NULL);
	}

	else
	{
		close(fd[1]);
		n = read(fd[0], line, MAXSIZE);
		write(STDOUT_FILENO, line, n);
	}

	return 0;
}



2

server.c

/*server.c*/
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*定义FIFO路径*/
#define FIFO "/tmp/myfifo"

int
main (int argc, char **argv)
{
  char buf_r[100];
  int fd;
  int nread;
  /*创建FIFO管道 */
  if ((mkfifo (FIFO, 0777) < 0) && (errno != EEXIST))
    printf ("cannot create fifoserver\n");
  printf ("Preparing for reading bytes...\n");

  memset (buf_r, 0, sizeof (buf_r));
  /*打开FIFO管道,不阻塞方式 */
  fd = open (FIFO, O_RDONLY | O_NONBLOCK, 0);
  if (fd == -1)
    {
      perror ("open");
      exit (1);
    }
  while (1)
    {
      memset (buf_r, 0, sizeof (buf_r));
      /*读管道,因为定义了非阻塞方式,故在此不会阻塞进程 */
      if ((nread = read (fd, buf_r, 100)) == -1)
	{
	  if (errno == EAGAIN)
	    printf ("no data yet\n");
	}
      printf ("read %s from FIFO\n", buf_r);
      sleep (1);
    }
  pause ();
  unlink (FIFO);
  return 0;
}

/*client.c*/
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 /*定义FIFO路径 */
#define FIFO "/tmp/myfifo"
int
main (int argc, char **argv)
{
  int i = 0;
  int fd = 0;
  char buf[100] = "";
  int nwrite;
  /*打开FIFO管道 */
  fd = open (FIFO, O_WRONLY | O_NONBLOCK);
  if (fd == -1)
    if (errno == ENXIO)
      printf ("open error; no reading process\n");
  /*判断有没有参数输入 */
  if (argc > 1)
    printf ("Please send something\n");
  /*复制参数输入 */

  for (i = 1; i < argc; ++i)
    {
      strcat (buf, argv[i]);
      strcat (buf, " ");
    }
  /*写到FIFO去 */
  if ((nwrite = write (fd, buf, 100)) == -1)
    {
      if (errno == EAGAIN)
	printf ("The FIFO has not been read yet.Please try later\n");

    }
  else
    /*输出写入的内容 */
    printf ("write %s to the FIFO\n", buf);
  return 0;
}

第一个父子间的通信,带有亲缘关系,而且是半双工的,第二个是任意两个进程,全双工的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值