一、无名管道Pipe
示意图:
1)管道就相当于队列的数据结构;
2)管道只适合半双工的通信方式;
3)只能用于具有亲缘关系的进程间通信;
4)管道操作不能同时读和写;读的时候要关闭写端;写的时候要关闭读端;
函数:
#include <unistd.h>
int pipe(int pipefd[2]);
说明:
参数:文件描述符:pipefd[0] 是读;pipefd[1] 是写;
返回值:0 成功;其他 失败;
举例:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int fd[2];
int pid;
char *w_count="hello world!";
char r_count[255];
if(pipe(fd)!=0)
{
printf("create pipe fail.\n");
return -1;
}
if((pid=fork())<0)
{
printf("create process fail.\n");
return -1;
}
else if(pid>0)
{
close(fd[0]);
write(fd[1],w_count,strlen(w_count));
close(fd[1]);
wait();
}
else
{
sleep(2);//等待父进程写操作;
close(fd[1]);
read(fd[0],r_count,255);
close(fd[0]);
printf("child read:%s\n",r_count);
}
return 0;
}
运行结果:
[root@localhost ~]# ./pipe
child read:hello world!
二、有名管道FIFO
在shell中,我们可以用mkfifo命令建立一个管道文件:“mkfifo myfifo”;
Fifo突破了pipe只能在父子进程中通信的局限性;这两个不相关的进程通过管道文件建立通信;
函数:
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
功能:建立管道文件;然后就可以对文件进行读写操作了;
参数:pathname是路径名称,mode是建立方式;
返回值:0