管道(pipe):分为匿名管道和命名管道
匿名管道:用于有亲缘关系的两个进程间通信
int pipe2(int pipefd[2], int flags);
#include <stdio.h>
#include <unistd.h>
#include <string.h>
//int pipe(int pipefd[2]); 2只是用于告诉只有两个元素有效
//把pipe两端看做两个文件,pipefd[0]读,pipefd[1]写
void main()
{
int pipefd[2];
pipe(pipefd);//相当于以读和写两种方式打开了两个文件
int pid=fork();
if(pid<0)
perror("fork()");
else if(0==pid)//子进程
{
char buf[20]="hello daddy";
write(pipefd[1],buf,sizeof(buf));//写//如果管道满了,也会阻塞
//也可以用fwrite写
read(pipefd[0],buf,sizeof(buf));//如果管道没有数据,父进程会等待
printf("父进程说:%s\n",buf);
close(pipefd[0]);
close(pipefd[1]);
}
else//父进程
{
char buf[20];
// wait(NULL);不需要显示等子进程 //阻塞
read(pipefd[0],buf,sizeof(buf));//如果管道没有数据,父进程会等待
printf("子进程说:%s\n",buf);
strcpy(buf,"hi boy");
write(pipefd[1],buf,sizeof(buf));
close(pipefd[0]);
close(pipefd[1]);
}
}
命名管道命名管道:可用于任意两个进程间通信
(一个在文件中写,另一个在文件中读,只要知道文件名就可以相互通信)
#include <iostream>
#include <fstream>//!!
using namespace std;
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main()
{
mkfifo("./data",00664);
ofstream of("./data");//发消息,创建文件,写入文件
of<<"有人吗?"; //消息没人收会阻塞
return 0;
}
#include <iostream>
#include <fstream>
using namespace std;
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#define PATH "./data"
int main()
{
ifstream inf("./data");//收消息,读文件
string msg; //文件中没有消息会阻塞
inf>>msg;
cout<<"收到消息:"<<msg<<endl;
return 0;
}