管道是Linux中很重要的一种通信方式,调用pipe()函数时,会在内核中开辟一块缓冲区即管道。该缓冲区的大小固定,为1页即4kb。
管道:不同的进程来访问同一资源
生命周期:随进程。
管道分为匿名管道和命名管道。
匿名管道:
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int pipefd[
2] = {
0,
0};
if((pipe(pipefd))<
0)
{
perror(
"pipe");
return
1;
}
pid_t id = fork();
if(id <
0)
{
perror(
"fork");
return
2;
}
else
if(id ==
0)
{
//child--write
close(pipefd[
0]);
const
char* msg =
"hello bit";
int count =
5;
while(count)
{
write(pipefd[
1],msg,
strlen(msg));
count--;
sleep(
1);
}
close(pipefd[
1]);
exit(
0);
}
else
{
//father--read
close(pipefd[
1]);
char buf[
128];
int count=
5;
while(count)
{
ssize_t _s=read(pipefd[
0],buf,
sizeof(buf)-
1);
if(_s>
0)
{
buf[_s]=
'\0';
printf(
"child->father:%s\n",buf);
}
else
{
close(pipefd[
0]);
return
3;
}
count--;
}
close(pipefd[
0]);
}
return
0;
}
注:匿名管道只能用于具有血缘关系的进程之间(多是父子进程)。
命名管道:
server.c:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
int main()
{
umask(
0);
if(mkfifo(
"./fifo",
0666|S_IFIFO)<
0)
{
perror(
"mkfifo");
return
1;
}
int fd=open(
"./fifo",O_RDONLY);
if(fd<
0)
{
perror(
"open");
return
2;
}
char buf[
128];
while(
1){
ssize_t s=read(fd,buf,
sizeof(buf));
if(s>
0)
{
buf[s]=
'\0';
printf(
"client: %s\n",buf);
}
else
if(s==
0)
{
printf(
"client is quit,sever also should quit\n");
break;
}
else{
perror(
"read");
return
3;
}
}
close(fd);
return
0;
}
client.c:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<string.h>
int main()
{
int fd=open(
"./fifo",O_WRONLY);
if(fd<
0)
{
perror(
"open");
return
2;
}
char buf[
128];
while(
1){
printf(
"please enter: ");
fflush(
stdout);
ssize_t s=read(
0,buf,
sizeof(buf));
if(s>
0)
{
buf[s-
1]=
'\0';
write(fd,buf,
strlen(buf));
}
}
close(fd);
return
0;
}