进程间通信(IPC,InterProcess Communication)是指在不同进程之间传播或交换信息。IPC的方式通常有管道(包括无名管道和命名管道)、消息队列、信号量、共享存储、Socket、Streams等。
一、管道特点:
-
它是半双工的(即数据只能在一个方向上流动),具有固定的读端和写端。
-
它只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。
-
它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write 等函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中
二、无名管道
#include <unistd.h>
int pipe(int pipefd[2]);
如果管道创建失败,则返回则为-1;
管道成功创建后,会创建2个文件描述符,fd[0]:只读,fd[1]:只写。
若要数据从父进程流向子进程,则关闭父进程的读端( fd[0]
)与子进程的写端( fd[1]
);反之,则可以使数据流从子进程流向父进程。
int main()
{
int fd[2];
int pid;
char buf[128];
if(pipe(fd)==-1){
printf("creat pipe fall\n");
}
pid=fork();
if(pid<0){
printf("creat pid fall\n");
}else if(pid>0){
sleep(3);
printf("this is father process\n");
close(fd[0]);
write(fd[1],"Hello world",strlen("Hello world"));
wait();
}else{
printf("this is son process\n");
close(fd[1]);
read(fd[0],buf,128);
printf("read is:%s\n",buf);
exit(0);
}
return 0;
}
父进程休眠3s时,子进程运行到read会阻塞,只有父进程休眠完write数据后,read才会执行。
三、FIFO
FIFO,也称为命名管道,它是一种文件类型。
1.特点:
(1)FIFO可以在无关的进程之间交换数据,与无名管道不同。
(2)FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。
2.函数原型:
#include <sys/types.h>
#include <sys/stat.h>int mkfifo(const char *pathname, mode_t mode);
mode 参数与open
函数中的 mode 相同
例子:
#include<stdio.h>
#include <sys/types.h>
#include<errno.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int nread=0;
char buf[128]={0};
if((mkfifo("./file1",0600)==0) && errno!=EEXIST){//判断创建是否成功
printf("creat mkfifo fail\n");
perror("why");
}
int fd=open("./file1",O_RDONLY);
printf("open success\n");
while(1){
nread=read(fd,buf,128);
printf("read %d zi jie ,nei rong is %s\n",nread,buf);
}
close(fd);
return 0;
}
#include<stdio.h>
#include <sys/types.h>
#include<errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
int main()
{
int cnt=0;
char *str="Hello World";
int fd=open("./file1",O_WRONLY);
printf("write open sucess\n");
while(1){
write(fd,str,strlen(str));
sleep(1);
if(cnt==5){
break;
}
}
close(fd);
return 0;
}
当open打开FIFO创建的文件时,如果用open只读的方式打开,则会阻塞直到某个进程以写的方式打开,只写 open 要阻塞到某个其他进程为读而打开它。
若指定了O_NONBLOCK
,则只读 open 立即返回。而只写 open 将出错返回 -1 如果没有进程已经为读而打开该 FIFO,其errno置ENXIO。
在两个终端编译运行可以看到如下结果:
学习笔记,仅供参考。