进程间通信(IPC,InterProcess Communication)是指在不同进程之间传播或交换信息。
IPC的方式通常有管道(包括无名管道和命名管道)、消息队列、信号量、共享内存、Socket、Streams等。其中 Socket和Streams支持不同主机上的两个进程IPC。
一、无名管道
1、特点
(1)它是半双工的(即数据只能在一个方向上流动),具有固定的读端和写端。
(2)它只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。
(3)它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write 等函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。
2、常用API
#include <unistd.h>
int pipe(int fd[2]); // 返回值:若成功返回0,失败返回-1
当一个管道建立时,它会创建两个文件描述符:
fd[0]为读而打开,fd[1]为写而打开。
3.编程示例
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd[2];
int pid;
char buf[128];
if(pipe(fd)== -1){//判断管道是否创建成功
printf("create pipe failed\n");
}
pid = fork();
if(pid < 0){//判断父子进程是否创建成功
printf("create child failed\n");
}
else if(pid > 0){ //父进程
sleep(3);
printf("this is father\n");
close(fd[0]);//关闭读端
write(fd[1],"hello from father",strlen("hello from father"));
wait();//等待子进程
}else{ //子进程
printf("this is child\n");
close(fd[1]);//关闭写端
read(fd[0],buf,128);
printf("read from father:%s\n",buf);
exit(0);//退出
}
return 0;
}
二、命名管道
FIFO,也称为命名管道,它是一种文件类型。
1、特点
(1)FIFO可以在无关的进程之间交换数据,与无名管道不同;
(2)FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。
2、常用API
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
返回值:成功返回0,出错返回-1
其中的 mode 参数与open
函数中的 mode 相同。一旦创建了一个 FIFO,就可以用一般的文件I/O函数操作它。
当 open 一个FIFO时,是否设置非阻塞标志(O_NONBLOCK
)的区别:
-
若没有指定
O_NONBLOCK
(默认),只读 open 要阻塞到某个其他进程为写而打开此 FIFO。类似的,只写 open 要阻塞到某个其他进程为读而打开它。 -
若指定了
O_NONBLOCK
,则只读 open 立即返回。而只写 open 将出错返回 -1 如果没有进程已经为读而打开该 FIFO,其errno置ENXIO。
3.编程示例
使用 FIFO 进行 IPC 的过程:
write.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int cnt;
char *str = "message from fifo";
int fd = open("./file",O_WRONLY);//以写打开一个FIFO
printf("write open success\n");
while(1){ //不断往FIFO中写
write(fd,str,strlen(str));
sleep(1);
if(cnt == 5){
break;
}
}
close(fd);
return 0;
}
read.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
int nread = 0;
char buf[1024] = {0};
if(mkfifo("./file",0600) == -1 && errno != EEXIST){//判断FIFO是否成功
printf("mkfifo failed\n");
perror("why");
}
int fd = open("./file",O_RDONLY);//以读打开FIFO
printf("open success\n");
while(1){ //不断的从FIFO中读
nread = read(fd,buf,30);
printf("read %d byte from fifo,context:%s\n",nread,buf);
}
close(fd);
return 0;
}