1.进程间通信介绍
1.1进程间通信目的
-
数据传输:一个进程需要将它的数据发送给另一个进程。
-
资源共享:多个进程之间共享同样的资源。
-
通知事件:一个进程需要向另一个或一组进程发送消息,通知它(它们)发生了某种事件(如进程终止时要通知父进程)。
-
进程控制:有些进程希望完全控制另一个进程的执行(如 debug 进程),此时控制进程希望能够拦截另一个进程的所有陷入和异常,并能够及时知道它的状态改变。
1.2进程间通信发展
-
管道
-
system v 进程间通信
-
posix 进程间通信
1.3 进程间通信分类
1.3.1管道
-
匿名管道 pipe
-
命名管道
1.3.2 system v ipc
-
system v 消息队列
-
system v 共享内存
-
system v 信号量
1.3.3 posix ipc
- 消息队列
-
共享内存
- 信号量
- 互斥量
- 条件变量
- 读写锁
2.管道
2.1什么是管道
-
管道是 unix 中最古老的进程间通信的形式。
-
我们把从一个进程连接到另一个进程的一个数据流称为一个 “ 管道”。
2.2匿名管道
#include <unistd.h>
功能:创建一无名管道
原型
int pipe(int fd[2]);
参数
fd:文件描述符数组,其中fd[0]表示读端, fd[1]表示写端
返回值:成功返回0,失败返回错误代码
2.3实例代码
例子:从键盘读取数据,写入管道,读取管道,写到屏幕
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
int fds[2];
char buf[100];
int len;
if (pipe(fds) == -1)
perror("make pipe"), exit(1);
// read from stdin
while (fgets(buf, 100, stdin))
{
len = strlen(buf);
// write into pipe
if (write(fds[1], buf, len) != len)
{
perror("write to pipe");
break;
}
memset(buf, 0x00, sizeof(buf));
// read from pipe
if ((len = read(fds[0], buf, 100)) == -1)
{
perror("read from pipe");
break;
}
// write to stdout
if (write(1, buf, len) != len)
{
perror("write to stdout");
break;
}
}
}
2.4用fork来共享管道原理
2.5站在文件描述符角度-深度理解管道
2.6站在内核角度-管道本质
所以,看待管道,就如同看待文件一样!管道的使用和文件一致,迎合了“linux一切皆文件思想”。
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#defifine err_exit(m) \ do \ { \ perror(m); \ exit(exit_failure); \ } while(0)
发表评论