进程间通信——消息传递(管道)

【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】

本篇是IPC开篇吧,最近开始研读进程间通信,感知Linux博大精深啊,一步一步来吧。今天先说最原始的通信方式管道,管道分两种,无名管道pipe和有名管道fifo。本篇参考UNIX网络编程之进程间通信相关源码,首先我们来了解无名管道pipe。

无名管道特点:

一、半双工的,数据只能向一个方向流动,需要双方通信时,需要建立起两个管道。

二、只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程)通信。

三、写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。

  

 


参考上图代码如下:

/*
** 双向全双工管道。
** 父:父进程把需要读取文件路径写入管道1,然后阻塞读取管道2,收到数据后打印出来
** 子:读取管道1父进程写入管道的路劲,打开后读取文件内容写入管道2
*/

#include "../myipc.h"
#define   MAXLINE   512

void client(int readfd, int writefd)
{
	size_t	len;
	ssize_t	n;
	char	buff[MAXLINE];

		/* 4read pathname */
	fgets(buff, MAXLINE, stdin);
	len = strlen(buff);		/* fgets() guarantees null byte at end */
	if (buff[len-1] == '\n')
		len--;				/* delete newline from fgets() */

		/* 4write pathname to IPC channel */
	write(writefd, buff, len);

		/* 4read from IPC, write to standard output */
	while ( (n = read(readfd, buff, MAXLINE)) > 0)
	{
		printf("Now read the path file data is :\n");
		write(STDOUT_FILENO, buff, n);
	}
}

void server(int readfd, int writefd)
{
	int		fd;
	ssize_t	n;
	char	buff[MAXLINE+1];

		/* 4read pathname from IPC channel */
	if ( (n = read(readfd, buff, MAXLINE)) == 0)
		//err_quit("end-of-file while reading pathname");
		perror("end-of-file while reading pathname");
	buff[n] = '\0';		/* null terminate pathname */

	if ( (fd = open(buff, O_RDONLY)) < 0) {
			/* 4error: must tell client */
		snprintf(buff + n, sizeof(buff) - n, ": can't open, %s\n",
				 strerror(errno));
		n = strlen(buff);
		write(writefd, buff, n);

	} else {
			/* 4open succeeded: copy file to IPC channel */
		while ( (n = read(fd, buff, MAXLINE)) > 0)
			write(writefd, buff, n);
		close(fd);
	}
}

int main(int argc, char **argv)
{
	int		pipe1[2], pipe2[2];
	pid_t	childpid;

	pipe(pipe1);	/* create two pipes */
	pipe(pipe2);

	if ( (childpid = fork()) == 0) {		/* child */
		close(pipe1[1]);
		close(pipe2[0]);

		server(pipe1[0], pipe2[1]);
		exit(0);
	}
		/* 4parent */
	close(pipe1[0]);
	close(pipe2[1]);

	client(pipe2[0], pipe1[1]);

	waitpid(childpid, NULL, 0);		/* wait for child to terminate */
	exit(0);
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值