目录
一、进程间通信(IPC)
1.概念:指在不同进程之间传播或交换信息。
2.IPC的方式:管道(包括无名管道和命名管道)、消息队列、信号量、共享存储、Socket、Streams等,其中Socket和Streams支持不同主机上的两个进程IPC。
二、无名管道
1.管道的本质
是内核中的一个缓存,当进程创建一个管道后,Linux会返回两个文件描述符,一个是写入端的描述符fd[1],一个是输出端的描述符fd[0],可以通过这两个文件描述符往管道写入和读取数据。
2.pipe函数
(1)函数原型:int pipe(int fd[2]);
(2) 功能:创建一个无名管道;
(3) 参数:fd[0] 读端 ;fd[1] 写端
(4) 返回值:成功返回0,失败 -1
3.管道的特点
3.1 它是半双工的,固定的读写端;
3.2 它只能用于具有亲缘关系的进程间的通信,(也就父子进程或兄弟进程之间)。
3.3 它可以看成是一种特殊的文件,对于它的读写也可以使用read、write函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。
4.代码示例
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
int main()
{
int fd[2];//两个文件描述符
int pid;
char Buf[20];
if(pipe(fd)<0){
printf("pipe Creat Error!\n");
}
pid = fork();//创建进程
if(pid < 0){
printf("Fork Error!\n");
}
else if(pid > 0){//父进程
sleep(3);
printf("this is father\n");
close(fd[0]);//关闭读端
write(fd[1],"Hello Word\n",20);
wait();//等待子进程退出
}
else{
printf("this is child\n");
close(fd[1]);//关闭写端
read(fd[0],Buf,20);
printf("father write,child read:%s\n",Buf);
exit(0);
}
return 0;
}
三、命名管道(FIPO)
1.无名管道只能由父子进程使用,但是通过命名管道,不相关的进程也能交换数据。FIPO是一种文件类型。
2.函数原型:
int mkfifo(const char *pathname,mode_t mode);
pathname:FIFO文件名
mode:属性
//其中mode参数与open函数中的mode相同
//一旦创建了FIFO,就可以用open打开它,一般的文件访问函数(close,read,write等)都可以用于FIFO
当open一个FIFO时,是否设置阻塞标志(O_NONBLOCK)的区别:
(1)若没有指定 O_NONBLOCK(默认)只读open要阻塞到某个其他进程为写而打开此FIFO,类似的,只写open要阻塞到某个其它进程为读而打开它。
代码示例:
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
// int mkfifo(const char *pathname, mode_t mode);
int main()
{
if((mkfifo("./file",0600) == -1) && errno != EEXIST){//创建命名管道
printf("mkfifo Creat fail!\n");
perror("why");
}
int fd = open("./file",O_RDONLY);//只读方式打开FIFO
printf("open success!\n");
return 0;
}
当只是去运行这段代码的话会阻塞到这边:
去以写的方式打开管道:
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
// int mkfifo(const char *pathname, mode_t mode);
int main()
{
int fd = open("./file",O_WRONLY);//可写的方式打开FIFO
printf("write success!\n");
return 0;
}
运行结果:
(2)若指定了O_NONBLOCK,则只读open立即返回,而只写open将出错返回-1,如果没有进程已经为读而打开改FIFO,则errno置ENXIO;