1. 管道文件是一个特殊文件,它由队列实现的。在文件IO中,创建、打开一个文件是由open函数实现,但是无名管道不能用open创建,对应的函数是pipe。
创建:pipe
读:read
写:write
关闭:close
无名管道的无名是指在它在文件系统中无文件名。
2. pipe:
函数形式:int pipe(int fd[2]);
功能:创建管道,为系统调用:unistd.h
参数:文件描述符。fd[0]是读端口,fd[1]是写端口。
返回:成功0,出错-1.
3. 实例1,创建管道:
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
int fd[2];
int ret;
ret=pipe(fd);
if(ret <0)
{
printf("creat pipe failure\n");
return -1;
}
printf("creat pipe sucess fd[0]=%d,fd[1]=%d\n",fd[0],fd[1]);
return 0;
}
执行结果:
alex@alex-virtual-machine:/extra/process/002$ gcc pipe_1.c
alex@alex-virtual-machine:/extra/process/002$ ls
a.out pipe_1.c pipe_2.c pipe_3.c
alex@alex-virtual-machine:/extra/process/002$ ./a.out
creat pipe sucess fd[0]=3,fd[1]=4
4.实例2,管道读写:
管道是以队列形式实现,管道内的东西读完就删了。如果管道内没有东西可读,则会阻塞。
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
int main()
{
int fd[2];
int ret;
char writebuf[]="hello linux";
char readbuf[128]={0};
ret=pipe(fd);
if(ret <0)
{
printf("creat pipe failure\n");
return -1;
}
printf("creat pipe sucess fd[0]=%d,fd[1]=%d\n",fd[0],fd[1]);
write(fd[1],writebuf,sizeof(writebuf));
//start read from pipe
read(fd[0],readbuf,128);
printf("readbuf=%s\n",readbuf);
close(fd[0]);
close(fd[1]);
return 0;
}
执行结果:
alex@alex-virtual-machine:/extra/process/002$ gcc pipe_2.c
alex@alex-virtual-machine:/extra/process/002$ ./a.out
creat pipe sucess fd[0]=3,fd[1]=4
readbuf=hello linux
alex@alex-virtual-machine:/extra/process/002$
5. 实例:读阻塞
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
int main()
{
int fd[2];
int ret;
char writebuf[]="hello linux";
char readbuf[128]={0};
ret=pipe(fd);
if(ret <0)
{
printf("creat pipe failure\n");
return -1;
}
printf("creat pipe sucess fd[0]=%d,fd[1]=%d\n",fd[0],fd[1]);
write(fd[1],writebuf,sizeof(writebuf));
//start read from pipe
read(fd[0],readbuf,128);
printf("readbuf=%s\n",readbuf);
//second read from pipe
memset(readbuf,0,128);
read(fd[0],readbuf,128);
printf("second read after\n");
close(fd[0]);
close(fd[1]);
return 0;
}
执行结果:
alex@alex-virtual-machine:/extra/process/002$ gcc pipe_3.c
alex@alex-virtual-machine:/extra/process/002$ ./a.out
creat pipe sucess fd[0]=3,fd[1]=4
readbuf=hello linux
^C