最常用的无名管道,有名管道,消息队列,信号,信号量,共享内存等进程间的通信方式。其实后面网络通信套字节 socket的方式也可以归为进程通行。
1.无名管道 pipe
- 从 UNIX 系统开始,无名管道的通信方式就存在,有点类似硬件中的串口,从最初的设计者定型之后,这种模型就一直延续到今天,说明无名管道当初设计的就极具科学性。不过无名管道有一定的局限性。
第一:它是属于半双工的通信方式;
第二:只有具有“亲缘关系”的的进程才能使用这种通信方式,也就是父进程和子进程之间。
无名管道通信首先需要使用 pipe 函数创建管道之后,两个进程之间才能通信。 - int pipe(int pipefd[2])
参数 pipefd[0]:用于读管道。
参数 pipefd[1]:用于写管道。
返回值:执行成功返回 0,失败返回-1。 - 例程
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
//进程读函数
void read_data(int *);
//进程写函数
void write_data(int *);
int main(int argc,char *argv[])
{
int pipes[2],rc;
pid_t pid;
rc = pipe(pipes); //创建管道
if(rc == -1){
perror("\npipes\n");
exit(1);
}
pid = fork(); //创建进程
switch(pid){
case -1:
perror("\nfork\n");
exit(1);
case 0:
read_data(pipes); //相同的pipes
default:
write_data(pipes); //相同的pipes
}
return 0;
}
//进程读函数
void read_data(int pipes[])
{
int c,rc;
//由于此函数只负责读,因此将写描述关闭(资源宝贵)
close(pipes[1]);
//阻塞,等待从管道读取数据
//int 转为 unsiged char 输出到终端
while( (rc = read(pipes[0],&c,1)) > 0 ){
putchar(c);
}
exit(0);
}
//进程写函数
void write_data(int pipes[])
{
int c,rc;
//关闭读描述字
close(pipes[0]);
while( (c=getchar()) > 0 ){
rc = write( pipes[1], &c, 1); //写入管道
if( rc == -1 ){
perror("Parent: write");
close(pipes[1]);
exit(1);
}
}
close( pipes[1] );
exit(0);
}
2.有名管道 fifo
- 无名管道只能用于有亲缘进程之间的通信,有名管道可以实现无亲缘关系的通信。
有名管道 fifo 给文件系统提供一个路径,这个路径和管道关联,只要知道这个管道路径,就可以进行文件访问,fifo 是指先进先出,也就是先写入的数据,先读出来。 - int mkfifo(const char pathname, mode_t mode);
参数pathname:路径名,管道名称。
参数 mode:管道的权限。
返回值:成功返回 0,错误返回-1。 - 例程
creatc.c 文件
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void filecopy(FILE *,char *);
int main(void)
{
FILE *fp1;
long int i = 100000;
char buf[] = "I want to study Linux!\n";
char *file1 = "data.txt";
printf("begin!\n");
if((fp1 = fopen(file1,"a+")) == NULL ){
printf("can't open %s\n",file1);
}
while(i--)
filecopy(fp1,buf);
fclose(fp1);
printf("over!\n");
return 0;
}
void filecopy(FILE *ifp,char *buf)
{
char c;
int i,j;
j = 0;
i = strlen(buf)-1;
while(i--){
putc(buf[j],ifp);
j++;
}
putc('\n',ifp);
}
readpipe.c 文件测试对有名管道的读
在这里插入代码片
本文深入探讨了进程间通信(IPC)的各种方式,包括无名管道、有名管道(fifo)、消息队列、信号、信号量和共享内存。通过具体实例,详细介绍了无名管道和有名管道的工作原理和使用方法,展示了如何在不同类型的进程中实现有效的数据交换。

936

被折叠的 条评论
为什么被折叠?



