目录:
1. 半双工管道
2. 命名管道
3. 消息队列
4. 信号量
5. 信号
6. 共享内存
不同通信机制的流程:
![](https://img.haomeiwen.com/i9257371/f34112103f2e73d0.png)
1 半双工管道
1.1 特点
- 管道把两个进程之间的标准输入和标准输出连接起来,为单向通信。
- 进程通过操作管道的两个文件描述符进行读写操作,一个进程进行写操作,另一个进程进行读操作,对管道的读写与一般的IO口一致。
-
管道的操作是阻塞性的,当管道中的数据未满时,可以一直向其中写入数据;管道中的数据达到上限时,写入操作会阻塞,直到有进程将管道中的数据读出才会继续写入。
半双工管道工作流程
1.2 pipe()函数
#include <stdio.h>
int pipe(int filedes[2]);
- 调用成功返回0,失败返回-1。
- fileds[2]用于保存管道返回的两个文件描述符,fileds[0]进行读操作,fileds[1]进行写操作。
1.3 pipe()例程
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int ret=-1;
int fd[2];
pid_t pid;
char string[]="hey,guy!";
char readbuf[80];
int *write_fd=&fd[1];
int *read_fd=&fd[0];
ret=pipe(fd);
if(ret==-1)
{
printf("pipe error!\n");
return -1;
}
pid=fork();
if(pid==-1)
{
printf("fork error!\n");
return -1;
}
if(pid==0)
{
close(*read_fd);
ret=write(*write_fd,string,strlen(string));
return 0;
}
else
{
close(*write_fd);
ret=read(*read_fd,readbuf,sizeof(readbuf));
printf("receive :%d, %s\n",ret,readbuf);
}
return 0;
}
运行结果:
receive:8, hey,guy!
网友评论