(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;
}