IPC通信_无名管道(PIPE)

无名管道只能在具有公共祖先的两个进程间使用,且建议半双工使用(因为历史上就是半双工,虽然有些系统支持全双工管道)

无名管道通过pipe函数创建

 

#include <unistd.h>
int pipe(int fd[2]);

 

其中:参数fd返回两个文件描述符,fd[0]只用来读,是输出,fd[1]只用来写,是输入。

举例:

#include <fcntl.h>  
#include <unistd.h>
#include <stdio.h> 
#include <stdlib.h>
// linux支持双通道?
int main()
{
	int fd[2];
	int pid = 0;
	int n = 0;
	char buf[128] = {0};
	if(pipe(fd) < 0)
	{
		printf("pipe failed\n");
		return -1;
	}
	if(pid = fork() == 0)
	{// 子进程
		printf("child print\n");
		close(fd[0]);
		write(fd[1],"hello,this is child\n",40);
	}
	else
	{// 父进程
		printf("father print\n");
		close(fd[1]);
		n = read(fd[0],buf,sizeof(buf));
		if(n > 0)
		{
			printf("father print:%s\n",buf);
		}
	}
	sleep(2);
	exit(0);	
}

  

posted @ 2020-02-02 22:27  ho966  阅读(156)  评论(0编辑  收藏  举报