单向无名管道:占用两个文件描述符(读,写),用于父子进程中
父写子读
#include <iostream>
using namespace std;
int main()
{
int fileds[2];
char buf[256];
pid_t pid;
if(pipe(fileds) < 0)
{
cout<<"pipe error"<<endl;
exit(-1);
}
if((pid=fork()) < 0)
{
cout<<"fork error"<<endl;
close(fileds[0]);
close(fileds[1]);
}
else
if(pid == 0)
{
close(fileds[1]);//0读1写,所以关闭1
memset(buf, 0, sizeof(buf));
read(fileds[0], buf, sizeof(buf));
cout<<"child read: "<<buf<<endl;
close(fileds[0]);
exit(0);
}
else
{
close(fileds[0]);
write(fileds[1], "hello", 5);
write(fileds[1], " world", 6);
close(fileds[1]);
}
}
双向无名管道:创建两个管道
#include <iostream>
using namespace std;
int main()
{
int fileds1[2], fileds2[2];
pid_t pid;
char buf[256]={};
if(pipe(fileds1)<0 || pipe(fileds2)<0)
{
cout<<"pipe error"<<endl;
exit(-1);
}
if((pid=fork()) < 0 )
{
cout<<"fork error"<<endl;
close(fileds1[0]);
close(fileds1[1]);
close(fileds2[0]);
close(fileds2[1]);
exit(-1);
}
if(pid == 0)
{
close(fileds1[1]);//关闭管道1的写
close(fileds2[0]);
memset(buf, 0, sizeof(buf));
read(fileds1[0], buf, sizeof(buf));
cout<<"child read: "<<buf<<endl;
write(fileds2[1], "hello parent", sizeof("hello parent"));
close(fileds1[0]);
close(fileds2[1]);
exit(0);
}
else
{
close(fileds1[0]);
close(fileds2[1]);
write(fileds1[1], "hello child", sizeof("hello child"));
memset(buf, 0, sizeof(buf));
read(fileds2[0], buf, sizeof(buf));
cout<<"parent read: "<<buf<<endl;
close(fileds1[1]);
close(fileds2[0]);
exit(0);
}
}
父进程的输出连接子进程的输入
#include <iostream>
using namespace std;
int main()
{
char buf[256]={};
pid_t pid;
int fileds[2];
if(pipe(fileds) < 0)
{
cout<<"pipe error"<<endl;
exit(-1);
}
if((pid=fork()) < 0)
{
close(fileds[0]);
close(fileds[1]);
cout<<"fork error"<<endl;
exit(-1);
}
else
if(pid == 0)
{
close(fileds[1]);
dup2(fileds[0], 0);//重定向标准输入为管道输出端
gets(buf);
cout<<"child read: "<<buf<<endl;
close(fileds[0]);
exit(0);
}
else
{
close(fileds[0]);
dup2(fileds[1], 1);
puts("hello child");
close(fileds[1]);
exit(0);
}
}
有名管道
发端
#include <iostream>#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int main()
{
mkfifo("a.fifo", 0600);//管道名通过命令行传递更合理
int fd = open("a.fifo", O_WRONLY);
if(fd < 0)
{
cout<<"error"<<endl;
return -1;
}
else
cout<<"pipe ready"<<endl;
for(;;)
{
cout<<"input a string:";
string str;
getline(cin, str);
write(fd, str.c_str(), str.size());
if(str == "bye")
break;
}
close(fd);
}
收端
#include <iostream>
#include <sys/stat.h>
#include <fcntl>
using namespace std;
int main()
{
mkfifo("a.fifo", 0600);
int fd = open("a.fifo", O_RDONLY);
if(fd < 0)
{
cout<<"error"<<endl;
return -1;
}
else
cout<<"pipe ready"<<endl;
for(;;)
{
char buf[100];
int n = read(fd, buf, 100);
buf[n] = '\0';
if(strcmp(buf, "bye") == 0)
break;
else
cout<<buf<<endl;
}
close(fd);
}