进程间通信(IPC,InterProcess Communication)是指在不同进程之间传播或交换信息。
IPC的方式通常有管道(包括无名管道和命名管道)、消息队列、信号量、共享存储、Socket、Streams等。其中 Socket和Streams支持不同主机上的两个进程IPC。(笔面会问。背)
一、管道(无名管道pipe)
管道,通常指无名管道,是 UNIX 系统IPC最古老的形式。
1、特点:
(1)它是半双工的(即数据只能在一个方向上流动),具有固定的读端和写端。
(2)它只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。
(3)它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write 等函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。
(4)管道里不存储数据。
2、原型:
1 #include <unistd.h>
2 int pipe(int fd[2]); // 返回值:若成功返回0,失败返回-1
当一个管道建立时,它会创建两个文件描述符:fd[0]为读而打开,fd[1]为写而打开。如下图:
要关闭管道只需将这两个文件描述符关闭即可。
3、例子
单个进程中的管道几乎没有任何用处。所以,通常调用 pipe 的进程接着调用 fork,这样就创建了父进程与子进程之间的 IPC 通道。如下图所示:
若要数据流从父进程流向子进程,则关闭父进程的读端(fd[0])与子进程的写端(fd[1]);反之,则可以使数据流从子进程流向父进程。
pipe 代码案例:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int fd[2];
int pid;
char *writeBuf="yl hen shuai!";
char readBuf[128];
if(pipe(fd)==-1){
printf("pipe faile\n");
}
pid=fork();
if(pid<0){
printf("fork failed\n");
}else if(pid>0){
sleep(3);
printf("father jin cheng\n");
close(fd[0]);
if(write(fd[1],writeBuf,strlen(writeBuf)+1)==-1){
printf("write failed\n");
}
wait();
}else{
printf("child jin cheng\n");
close(fd[1]);
int readId=read(fd[0],readBuf,128);
if(readId==-1){
printf("read failed\n");
}
printf("read from fathar %d byte:%s\n",readId,readBuf);
exit(-1);
}
return 0;
}
结果:
child jin cheng
father jin cheng
read from fathar 14 byte:yl hen shuai!
二、FIFO(命名管道)
FIFO,也称为命名管道,它是一种文件类型。
1、特点
FIFO可以在无关的进程之间交换数据,与无名管道不同。
FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。
2、原型
1 #include <sys/stat.h>
2 // 返回值:成功返回0,出错返回-1
3 int mkfifo(const char *pathname, mode_t mode);
其中的 mode 参数与open函数中的 mode 相同。一旦创建了一个 FIFO,就可以用一般的文件I/O函数操作它。
当 open 一个FIFO时,是否设置非阻塞标志(O_NONBLOCK)的区别:
若没有指定O_NONBLOCK(默认),只读 open 要阻塞到某个其他进程为写而打开此 FIFO。类似的,只写 open 要阻塞到某个其他进程为读而打开它。
若指定了O_NONBLOCK,则只读 open 立即返回。而只写 open 将出错返回 -1 如果没有进程已经为读而打开该 FIFO,其errno置ENXIO。
案例:
read 端代码:
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
int main()
{
int fd;
char readBuf[128];
int nread;
if(mkfifo("./file1",0600)==-1 && errno !=EEXIST){
printf("creat file1 failed\n");
}
fd=open("./file1",O_RDONLY);
if(fd==-1){
printf("open file1 failed\n");
}
nread=read(fd,readBuf,128);
printf("read%d byte from write:%s\n",nread,readBuf);
close(fd);
return 0;
}
~
write 端代码:
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
int main()
{
int fd;
char *writeBuf="yl hen shuai!";
fd=open("./file1",O_WRONLY);
if(fd==-1){
printf(