IPC是各种进程间通信方式的统称。
进程间通信:是指在不同进程之间传播或交换信息。
IPC的方式通常有:
单机:管道(包括无名管道和命名管道)、消息队列、信号量、共享存储、
多机:Socket、Streams等
1、管道:通常指无名管道,是UNIX系统IPC最古老的形式。
特点:①它是半双工的(数据只能在一个方向上流动),具有固定的读端和写端。
· ②只能用于具有亲缘关系的进程之间的通信(也就是父子进程或者兄弟进程)
③它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write等函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。
建立管道的api:
#include <unistd.h>
int pipe(int fd[2]);
fd[0]为读而打开,fd[1]为写而打开
要关闭管道,只需要将这两个文件描述符关闭即可close(fd[0]);close(fd[1]);
fork:返回值<0表示创建失败;返回值>0,程序为父进程;返回值=0,程序为子进程;
无名管道代码实现:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd[2];
int pid;
char buf[128];
// int pipe(int pipefd[2]);
if(pipe(fd)==-1){
printf("creat pipe fail\n");
}
pid=fork();
if(pid<0){
printf("creat child fail\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(NULL);
}
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;
}
编译运行结果:
this is child
//当管道为空,读数据的子进程会堵塞,3s后父进程写入数据,子进程读取数据打印出来
this is father
read from father:hello from father