linux学习笔记6-匿名管道

匿名管道

   匿名管道是半双工,只能读或者写.匿名管道只能用在有共同的父进程的进程间使用.比如fork和execve的进程中使用

匿名管道使用

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

int main(int argc,char *argv[])
{
	int fd[2];       //声明长度为2的数组,存放管道的描述符,第一个是读取的,第二个是写入的
	char buf[128];
	int len;
	pipe(fd);
	memset(buf,0,sizeof(buf));
	pid_t pid = fork();
	
	if(pid == -1)
	{
	   return -1;
	}
	else if(pid == 0)
	{
		close(fd[1]);  //因为匿名管道是半双工的,同时只能读或写,所以要先关闭写入的管道
		len= read(fd[0],buf,sizeof(buf)); //根据管道描述符读取管道中的数据
		if(len > 0)
		{
		    printf("str len=%d\n",len);
		    write(STDOUT_FILENO,buf,len);  //写入终端中
		   //printf(buf);
		}
		close(fd[0]);   //和文件一样,使用完一定要关闭
	}
	else 
	{
		close(fd[0]);       //在父进程进行写入,要先关闭
		strcpy(buf,"hello pipe!\n");
		write(fd[1],buf,sizeof(buf));
		close(fd[1]);
		waitpid(pid,NULL,0);
	}

	return 0;
}


秋风 2016-11-23