linux进程间通信-匿名半双工管道

来源:互联网 发布:东莞seo外包 编辑:程序博客网 时间:2024/05/14 16:34

原文链接http://blog.csdn.net/happyanger6/article/details/7455583

匿名管道没有名字,对于管道中使用的文件描述符没有路径名,也就是不存在任何意义上的文件,它们只是在内存中跟某一个索引节点相关联的两个文件描述符。



主要特性:
1.数据只能在一个方向上移动。

2.只能在具有公共祖先的进程间通信,即或是父子关系进程间、或是在兄弟关系进程间。


打开或关闭:

#include<unistd.h>
int pipe(int fd[2]);
参数int fd[2]为一个长度为2的文件描述符数组,fd[0]是读出端,fd[1]是写入端。
函数返回0表示成功,-1表示失败.
当函数成功返回,自动维护了一个从fd[1]到fd[0]的数据通道。


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


int main(void)
{
int fd[2];
char str[256];
if( (pipe(fd))<0)
{
printf("pipe error\n");
return -1; 
}
write(fd[1],"create!\n",8);
read(fd[0],str,sizeof(str));
printf("read from fd[1] are [%s]\n",str);
printf("pipe file descriptors are %d  %d\n",fd[0],fd[1]);
close(fd[0]);
close(fd[1]);
return 0;
}


读写操作(父子进程间)

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


int main(void)
{
char buff[256+1];
char *str="I am father";
int fd[2];
pid_t pid;

if(pipe(fd)<0)
{
printf("pipe error\n");
return -1; 
}

if( (pid=fork())<0)
{
printf("fork error\n");
return -2;
}

if(pid>0)/*father*/
{
close(fd[0]);  /*关闭读端*/
write(fd[1],str,strlen(str));
exit(0);
}
else /*son*/
{
close(fd[1]); /*关闭写端*/
memset(buff,0,sizeof(buff));
read(fd[0],buff,sizeof(buff));
printf("Son read from father【%s】\n",buff);
exit(0);
}
}


标准C函数操作:

#include <stdio.h>


FILE *popen(const char* command,const char* mode);
int pclose(FILE *stream);


popen函数先执行创建一个管道,然后调用fork创建子进程,紧接着执行一个exec调用,调用/bin/sh -c来执行参数
command中的命令字符串,然后返回一个标准的I/O文件指针。返回的文件指针类型与mode有关.
如果参数是r,则文件指针连接到command的标准输出;
如果参数是w,则文件指针连接到command的标准输入.


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

int main(void)
{
FILE* fp;
char *cmd = "cat file1";
char buff[256+1];
 
if( (fp=popen(cmd,"r"))==NULL)
{
printf("popen error\n");
return -1;
}
 
while(fgets(buff,sizeof(buff),fp)!=NULL)
{
printf("%s\n",buff);
memset(buff,0,sizeof(buff));
}
pclose(fp);
return 0;
}