(1)程序通信:程序之間是彼此獨立的,為實作彼此獨立的程序的通信,我們給他們配置設定一片公共的記憶體空間(公共區的提供者不同,通信方式也就不同)。

(2)管道的特性
a.管道通信是單向的
b.匿名管道常用于父子程序的
c.管道是面向位元組流的(發送方發送的方式和接受方接收方式不要求一樣,比如A一次發50個位元組,可B可以一次接收5個,接收10次)
d.管道的生命周期随程序
e.管道自帶同步機制
(3)代碼實作:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<string.h>
int main()
{
int pipef[2]={0,0}; // 0表示讀(像圓圓的眼睛)1表示寫(像我們的筆)
if( pipe(pipef)<0)
{
printf("pipe false");
exit(0);
}
else{
pid_t id=fork(); //fork()函數建立程序
if(id==0) //子程序
{
char *buf="hello world\n";
close(pipef[0]); //我們讓子程序寫,關掉管道的讀
int count=5;
while(count--)
{
write(pipef[1],buf,strlen(buf));
sleep(1);
}
close(pipef[1]);
}
else //父程序
{
close(pipef[1]); //關閉了父程序的寫
char buff[28];
while(1)
{
ssize_t s= read(pipef[0],buff,sizeof(buff-1));
buff[s]='\0';
if(s>0)
printf("%s",buff);
if(s==0)
{
close(pipef[0]);
return;
}
}
close(pipef[0]); //使用完之後記得關閉管道讀
}
}
return 0;
}