进程间通讯有四种方式:信号量、管道、消息队列、共享内存
我们以前已经介绍过了信号量,今天我们着重介绍一下管道。
管道可以分为有名管道和无名管道。
有名管道
有名管道利用管道文件实现进程间通讯,管道文件仅仅是磁盘上的一个文件标识,其真实数据存储在内存上。
1.命令:mkfifo filename
2.函数:int mkfifo();
对于管道文件的打开操作,必须是有读有写的。否则,open函数会阻塞。
对于管道文件指向的内存中的数据,一旦被读,则数据就“不存在”了 。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
#include<assert.h>
int main()
{
int fda=open("./FIFO",O_WRONLY);
assert(fda!=-1);
char buff[128];
int n=0;
while(1)
{
printf("Input sentence:");
scanf("%s",buff);
n=write(fda,buff,strlen(buff)+1);
if(n <= 0 || !strncmp(buff,"end",3))
{
break;
}
}
close(fda);
}
#include<stdio.h>
#include&l