匿名管道代码实现:
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
using namespace std;
int main()
{
int fd[2]={0};
if (pipe(fd) < 0)
{
perror("pipe");
return 1;
}
pid_t pid = fork();
if(pid<0)
perror("fork");
else if(pid>0)
{
close(fd[1]);
char buff[64];
while (1)
{
ssize_t s = read(fd[0], buff, sizeof(buff));
if (s > 0)
{
buff[s] = '\0';
cout<<"father reads:"<<buff<<endl;
}
else if (s == 0)
{
perror("already read all");
break;
}
else{
perror("read error");
break;
}
}
}
else
{
close(fd[0]);
while(1)
{
string message;
cout<<"son says: ";
cin>>message;
write(fd[1],message.c_str(),strlen(message.c_str()));
sleep(1);
}
}
}
注:
1.匿名管道仅限有亲缘关系的进程间通信。
2.匿名管道写进的数据不会写入磁盘,仅在内存中。
3.匿名管道只能单向通信。
4.写进程一直写而读进程不读,那么会使写进程挂起。
5.读进程一直读而写进程不写,那么会使读进程挂起。
6.写进程写完后关闭。读进程读完后继续执行后续任务不会挂起。
7.读进程关闭,而写进程一直写,那么系统会发送SIGPIPE信号终止进程。