小峰的LINUX的学习笔记
进程间通信(pipe、fifo、文件)
1. 进程间通信(IPC)
在进程间完成数据传输需要借助操作系统提供的特殊方法,如:文件、管道、信号、共享内存、消息队列、嵌套字、命名管道等。随着发展,一些方法由于自身设计缺陷被淘汰或者弃用。现今常用的进程通信方式有:
- 管道(使用最简单)
- 信号(开销最小)
- 共享映射区(无血缘关系)
- 本地套接字(最稳定)
2. 管道pipe
一种最基本的IPC机制,作用于有血缘关系的进程之间,完成数据传递。调用pipe系统函数即可创建一个管道。有如下特质:
- 本质是一个伪文件
- 由两个文件描述符引用,一个表示读端,一个表示写端。
- 规定数据从管道的写端流入管道,从读端流出
管道的原理:实为内核使用环形队列机制,借助内核缓冲区(4k)实现
管道的局限性:
- 数据不能进程自己写,自己读
- 管道中数据不可反复读取。一旦读走,管道中不再存在。
- 采用半双工通信方式,数据只能在单方向上流动
- 只能在有公有祖先的进程间使用管道
常见的通信方式: 单工通信、半双工通信、全双工通信
2.1 pipe 函数原型及头文件包含
man 2 pipe
#include<unistd.h>
int pipe(int pipefd[2]);
返回值:
成功---- 0
失败-----1 设置errno
fd[0]:读端
fd[1]:写端
2.2 父子进程通过 pipe 通信( demo )
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string.h>
int main(int argc, char * argv [ ])
{
int ret,num;
int pipefd[2];
pid_t pid;
char* str="hello pipe\n";
char buff[1024];
ret = pipe(pipefd);
if (ret == -1)
{
perror("pipe error\n");
exit(1);
}
pid = fork();
if(pid > 0)
{
close(pipefd[0]);
write(pipefd[1], str, strlen(str));
close(pipefd[1]);
}
if (pid == 0)
{
close(pipefd[1]);
num= read(pipefd[0],buff, sizeof(buff));
write(STDOUT_FILENO, buff, num);
close(pipefd[0]);
}
return 0;
}
子进程读取管道内容,并在 STDOUT 输出,成功!!!
2.3 管道读写行为
-
读管道
1.管道有数据,read返回实际读到的字节数
2.管道无数据:
1 )无写端,read返回0
2)有写端,read阻塞等待 -
写管道
1.管道读端全部关闭,进程异常终止(也可使用捕捉SIGPIPE信号,使进程不终止)
2.管道读端没有全部关闭:
1) 管道已满,write阻塞
2)管道未满,write将数据写入,并返回实际写入的字节数
2.4 demo 父子进程间pipe通信 实现 ls | wc -l 的功能
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<errno.h>
void sys_error(const char* str)
{
perror(str);
exit(1);
}
int main(int argc, char * argv [ ])
{
int ret;
int pipefd[2];
pid_t pid;
ret = pipe(pipefd);
if (ret == -1)
{
sys_error("pipe error\n");