进程通信 无名管道:
1.管道是半双工的,数据只能向一个方向流动;需要双方通信时,需要建立起两个管道;只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程)。
2.单独构成一种独立的文件系统:管道对于管道两端的进程而言,就是一个文件,但它不是普通的文件,它不属于某种文件系统,而是自立门户,单独构成一种文件系统,并且只存在与内存中。
3.数据的读出和写入:一个进程向管道中写的内容被管道另一端的进程读出。写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。(有点像队列哈)
原型:int pipe(int fd[2])
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd[2];
int pid;
char *buf = "====this from father===";
char readBuf[128];
if(pipe(fd) == -1){
printf("creat pipe fail\n");
}
pid = fork();
if(pid<0){
printf("creat chiled fail\n");
}else if(pid>0){
sleep(3);
printf("this is father\n");
close(fd[0]); //关闭管道的读
write(fd[1],buf,strlen(buf)); //向管道里面写
wait();
}else{
printf("this is chiled\n");
close(fd[1]); //关闭管道的写
read(fd[0],readBuf,strlen(buf)); //向管道里面读取数据
printf("%s\n",readBuf);
exit(0);
}
}
运行结果为: