Linux系统编程_进程间通信第1天:IPC、无名管道pipe和命名管道mkfifo(半双工)、消息队列msgget(全双工)

本文主要是介绍Linux系统编程_进程间通信第1天:IPC、无名管道pipe和命名管道mkfifo(半双工)、消息队列msgget(全双工),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 进程间通信概述(427.1)

在这里插入图片描述

2. 管道通信原理(428.2)

  • 进程间的五种通信方式介绍
    • https://blog.csdn.net/wh_sjc/article/details/70283843
  • 进程间通信(IPC,InterProcess Communication):在不同进程之间传播或交换信息(*面试会问)
    • IPC的方式通常有管道(无名管道和命名管道)、消息队列、信号量、共享存储、Socket、Streams等。其中 Socket和Streams支持不同主机上的两个进程IPC。

管道,通常指无名管道,是 UNIX 系统IPC最古老的形式

2.1 特点

  1. 它是半双工的(即数据只能在一个方向上流动),具有固定的读端和写端。
  2. 它只能用于具有亲缘关系的进程之间的通信(也是父子进程或者兄弟进程之间)。
  3. 它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write 等函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。

2.2 原型

#include <unistd.h>
int pipe(int fd[2]);    // 返回值:若成功返回0,失败返回-1
  • 当一个管道建立时,它会创建两个文件描述符:fd[0]为读而打开,fd[1]为写而打开。如下图:
  • 要关闭管道只需将这两个文件描述符关闭即可。
    在这里插入图片描述

2.3 例子

  • 单个进程中的管道几乎没有任何用处。所以,通常调用 pipe 的进程接着调用 fork,这样就创建了父进程与子进程之间的 IPC 通道。如下图所示:
  • 若要数据流从父进程流向子进程,则关闭父进程的读端(fd[0])与子进程的写端(fd[1]);反之,则可以使数据流从子进程流向父进程。

在这里插入图片描述

#include<stdio.h>
#include<unistd.h>int main(){int fd[2];  // 两个文件描述符pid_t pid;char buff[20];if(pipe(fd) < 0)  // 创建管道printf("Create Pipe Error!\n");if((pid = fork()) < 0)  // 创建子进程printf("Fork Error!\n");else if(pid > 0){  // 父进程close(fd[0]);  // 关闭读端write(fd[1],"hello world\n",12);}else{			   //子进程close(fd[1]);  // 关闭写端read(fd[0],buff,20);printf("%s",buff);}return 0;
}

在这里插入图片描述

3. 管道编程实战(429.3)(无名管道)

  • IPC/demo1.c(无名管道,父进程向子进程写入字符串)
#include <stdio.h>
#include <unistd.h>//标准c库 pipe fork
#include <string.h>
#include <stdlib.h>//标准c库 exit
#include <sys/types.h>
#include <sys/wait.h>//waitint main(){int fd[2];pid_t pid;char buf[128];
//	int pipe(int pipefd[2]);if(pipe(fd) == -1){   //创建管道printf("creat pipe failed\n");}pid = fork();         //创建子进程if(pid<0){printf("creat child failed\n");}else if(pid > 0){     //父进程sleep(3);		  //休眠确保子进程先运行,到read时阻塞,3s后父进程往下走printf("this is father\n");close(fd[0]); //关闭读端write(fd[1],"hello from father",strlen("hello form 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;
}

在这里插入图片描述

4. 创建命名管道(4)

FIFO,也称为命名管道,它是一种文件类型(半双工)

4.1 特点

  • FIFO 可以在无关的进程之间交换数据,与无名管道不同。
  • FIFO 有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。

4.2 原型

#include <sys/stat.h>
// 返回值:成功返回0,出错返回-1
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。

4.3 例子

  • FIFO 的通信方式类似于在进程中使用文件来传输数据,只不过 FIFO 类型文件同时具有管道的特性。在数据读出时,FIFO 管道中同时清除数据,并且“先进先出”。下面的例子演示了使用 FIFO 进行 IPC 的过程:
  • IPC/demo2.c(仅创建)
#include <sys/types.h>
#include <sys/stat.h>//mkfifo的int main(){//int mkfifo(const char *pathname, mode_t mode);mkfifo("./file",0600);//创建管道,权限为可读可写return 0;
}
  • IPC/demo3.c(简单调试:文件已存在,错误)
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>int main(){//int mkfifo(const char *pathname, mode_t mode);int ret = mkfifo("./file",0600);if(ret == 0){printf("mkfifo suscceess\n");}if(ret == -1){printf("mkfifo failed\n");perror("why");}		return 0;
}

在这里插入图片描述

  • IPC/demo4.c(效果同demo3)
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include<errno.h>int main(){
//int mkfifo(const char *pathname, mode_t mode);if( (mkfifo("./file",0600) == -1) && errno==EEXIST){printf("mkfifo failed\n");perror("why");}else{if(errno= =EEXIST){printf("file exists\n");}elseprintf("mkfifo suscceess\n");}		return 0;
}

在这里插入图片描述

  • IPC/demo5.c(创建管道,且只有在错误不是 EEXIST 时才打印错误消息)
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include<errno.h>int main(){
//int mkfifo(const char *pathname, mode_t mode);if( (mkfifo("./file",0600) == -1) && errno!=EEXIST){//只有在错误不是 EEXIST 时才打印错误消息perror("mkfifo failed");}return 0;
}

5. 命名管道的数据通信编程实现(430.5)

  • IPC/demo6.c(没有指定O_NONBLOCK(默认),只读 open 要阻塞到某个其他进程为写而打开此 FIFO)
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include<errno.h>
#include <fcntl.h>int main(){
//int mkfifo(const char *pathname, mode_t mode);if( (mkfifo("./file",0600) == -1) && errno!=EEXIST){printf("mkfifo failuer\n");perror("why");}int fd = open("./file",O_RDONLY);//若没有指定O_NONBLOCK(默认)printf("open success\n");//只读 open 要阻塞到某个其他进程为写而打开此 FIFO//close(fd);return 0;
}
  • IPC/writedemo6.c(没有指定O_NONBLOCK(默认),只写 open 要阻塞到某个其他进程为读而打开它)
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include<errno.h>
#include <fcntl.h>int main(){int fd = open("./file",O_WRONLY);//若没有指定O_NONBLOCK(默认)printf("write open success\n");//只写 open 要阻塞到某个其他进程为读而打开它//close(fd);return 0;
}
  • IPC/read.c(读5次)
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h> // O_WRONLY open
#include <string.h>//strlen
#include <unistd.h>//write
//int mkfifo(const char *pathname, mode_t mode);
int main(){char buf[30] = {0};//int nread = 0;int cnt = 0;if( (mkfifo("./file",0600) == -1) && errno!=EEXIST){//创建fifo管道printf("mkfifo failed\n");perror("why");}int fd = open("./file",O_RDONLY);printf("open success\n");while(1){int nread = read(fd,buf,30);//读内容printf("read %d byte from fifo,context:%s\n",nread,buf);cnt++;if(cnt == 5){break;	}}close(fd);return 0;
}
  • IPC/write.c(写5次)
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h> // O_WRONLY open
#include <string.h>//strlen
#include <unistd.h>//write
//int mkfifo(const char *pathname, mode_t mode);
int main(){int cnt = 0;char *str = "I'm Message from fifo_write";int fd = open("./file",O_WRONLY);printf("write open success\n");while(1){write(fd, str, strlen(str));//写内容cnt++;sleep(1);if(cnt == 5){break;	}}close(fd);return 0;
}

在这里插入图片描述

6. 消息队列的通信原理(6)

消息队列,是消息的链接表,存放在内核中。一个消息队列由一个标识符(即队列ID)来标识

特点

  1. 消息队列是面向记录的,其中的消息具有特定的格式以及特定的优先级。
  2. 消息队列独立于发送与接收进程。进程终止时,消息队列及其内容并不会被删除。
  3. 消息队列可以实现消息的随机查询,消息不一定要以先进先出的次序读取,也可以按消息的类型读取。
    在这里插入图片描述

7. 消息队列相关api(431.7)

在这里插入图片描述
在这里插入图片描述

原型

#include <sys/msg.h>
// 创建或打开消息队列:成功返回队列ID,失败返回-1
int msgget(key_t key, int flag);//通过key(非负数 索引值)找到对应消息队列,打开队列的方式//返回值是消息队列的标识符
// 添加消息:成功返回0,失败返回-1
int msgsnd(int msqid, const void *ptr, size_t size, int flag);//flag为0是默认阻塞的方式添加消息
// 读取消息:成功返回消息数据的长度,失败返回-1
int msgrcv(int msqid, void *ptr, size_t size, long type,int flag);//long type消息类型,用于找到对应消息,flag为0是默认阻塞的方式读取消息
// 控制消息队列:成功返回0,失败返回-1
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
  • 在以下两种情况下,msgget将创建一个新的消息队列:
    • 如果没有与键值 key 相对应的消息队列,并且 flag 中包含了 IPC_CREAT 标志位。
    • key 参数为 IPC_PRIVATE。
  • 函数 msgrcv 在读取消息队列时,type 参数有下面几种情况:
    • type == 0,返回队列中的第一个消息;
    • type > 0,返回队列中消息类型为 type 的第一个消息;
    • type < 0,返回队列中消息类型值小于或等于 type 绝对值的消息,如果有多个,则取类型值最小的消息。
  • 可以看出,type 值非 0 时用于以非先进先出次序读消息。也可以把 type 看做优先级的权值。(其他的参数解释,请自行Google之)
    在这里插入图片描述

8. 消息队列编程收发数据(432.8)

在这里插入图片描述

  • IPC/msgGet.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
//       int msgget(key_t key, int msgflg);
//       int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
//       ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
struct msgbuf{long mtype;       /* message type, must be > 0 */char mtext[256];    /* message data */
};int main(){struct msgbuf readBuf;	int msgId = msgget(0x1234,IPC_CREAT|0777);//创建/打开消息队列,通过key找到对应消息队列,可读可写可执行if(msgId == -1 ){printf("get que failed\n");//创建/打开失败}msgrcv(msgId, &readBuf,sizeof(readBuf.mtext),888,0);//读取消息	printf("read from que:%s\n",readBuf.mtext);struct msgbuf sendBuf = {988,"thank you for reach"};msgsnd(msgId,&sendBuf,strlen(sendBuf.mtext),0);//添加消息return 0;
}
  • IPC/msgSend.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
//       int msgget(key_t key, int msgflg);
//       int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
//       ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
struct msgbuf {long mtype;       /* message type, must be > 0 */char mtext[256];    /* message data */
};int main(){struct msgbuf sendBuf = {888,"this is message from quen"};	int msgId = msgget(0x1234, IPC_CREAT|0777);//创建/打开消息队列,通过key找到对应消息队列,可读可写可执行if(msgId == -1 ){printf("get que failed\n");}msgsnd(msgId,&sendBuf,strlen(sendBuf.mtext),0);//添加消息printf("send over\n");struct msgbuf readBuf;msgrcv(msgId,&readBuf,sizeof(readBuf.mtext),988,0);//读取消息printf("reaturn from get:%s\n",readBuf.mtext);return 0;
}

9. 键值生成及消息队列移除(9)

在这里插入图片描述

  • IPC/msgGet.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
//       int msgget(key_t key, int msgflg);
//       int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
//       ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
//int msgctl(int msqid, int cmd, struct msqid_ds *buf);
struct msgbuf{long mtype;       /* message type, must be > 0 */char mtext[256];    /* message data */
};int main(){struct msgbuf readBuf;	key_t key;key = ftok(".",'m');printf("key=%x\n",key);int msgId = msgget(key,IPC_CREAT|0777);//创建/打开消息队列,通过key找到对应消息队列,可读可写可执行if(msgId == -1 ){printf("get que failuer\n");}//memset(&readBuf,0,sizeof(struct msgbuf));msgrcv(msgId, &readBuf,sizeof(readBuf.mtext),888,0);//读取消息	printf("read from que:%s\n",readBuf.mtext);struct msgbuf sendBuf = {988,"thank you for reach"};msgsnd(msgId,&sendBuf,strlen(sendBuf.mtext),0);//添加消息msgctl(msgId,IPC_RMID,NULL);//控制消息队列,将消息队列从内核中删除return 0;
}
  • IPC/msgSend.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
//       int msgget(key_t key, int msgflg);
//       int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
//       ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
//int msgctl(int msqid, int cmd, struct msqid_ds *buf);
struct msgbuf {long mtype;       /* message type, must be > 0 */char mtext[256];    /* message data */
};int main(){struct msgbuf sendBuf = {888,"this is message from quen"};	key_t key;key = ftok(".",'m');printf("key=%x\n",key);int msgId = msgget(key, IPC_CREAT|0777);//创建/打开消息队列,通过key找到对应消息队列,可读可写可执行if(msgId == -1 ){printf("get que failuer\n");}msgsnd(msgId,&sendBuf,strlen(sendBuf.mtext),0);//添加消息printf("send over\n");struct msgbuf readBuf;//memset(&readBuf,0,sizeof(struct msgbuf));msgrcv(msgId,&readBuf,sizeof(readBuf.mtext),988,0);//读取消息printf("reaturn from get:%s\n",readBuf.mtext);msgctl(msgId,IPC_RMID,NULL);//控制消息队列,将消息队列从内核中删除return 0;
}

这篇关于Linux系统编程_进程间通信第1天:IPC、无名管道pipe和命名管道mkfifo(半双工)、消息队列msgget(全双工)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/240821

相关文章

Linux下如何使用C++获取硬件信息

《Linux下如何使用C++获取硬件信息》这篇文章主要为大家详细介绍了如何使用C++实现获取CPU,主板,磁盘,BIOS信息等硬件信息,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录方法获取CPU信息:读取"/proc/cpuinfo"文件获取磁盘信息:读取"/proc/diskstats"文

Linux内核参数配置与验证详细指南

《Linux内核参数配置与验证详细指南》在Linux系统运维和性能优化中,内核参数(sysctl)的配置至关重要,本文主要来聊聊如何配置与验证这些Linux内核参数,希望对大家有一定的帮助... 目录1. 引言2. 内核参数的作用3. 如何设置内核参数3.1 临时设置(重启失效)3.2 永久设置(重启仍生效

kali linux 无法登录root的问题及解决方法

《kalilinux无法登录root的问题及解决方法》:本文主要介绍kalilinux无法登录root的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录kali linux 无法登录root1、问题描述1.1、本地登录root1.2、ssh远程登录root2、

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

SpringKafka错误处理(重试机制与死信队列)

《SpringKafka错误处理(重试机制与死信队列)》SpringKafka提供了全面的错误处理机制,通过灵活的重试策略和死信队列处理,下面就来介绍一下,具有一定的参考价值,感兴趣的可以了解一下... 目录引言一、Spring Kafka错误处理基础二、配置重试机制三、死信队列实现四、特定异常的处理策略五

Linux ls命令操作详解

《Linuxls命令操作详解》通过ls命令,我们可以查看指定目录下的文件和子目录,并结合不同的选项获取详细的文件信息,如权限、大小、修改时间等,:本文主要介绍Linuxls命令详解,需要的朋友可... 目录1. 命令简介2. 命令的基本语法和用法2.1 语法格式2.2 使用示例2.2.1 列出当前目录下的文

利用Python快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

在Android平台上实现消息推送功能

《在Android平台上实现消息推送功能》随着移动互联网应用的飞速发展,消息推送已成为移动应用中不可或缺的功能,在Android平台上,实现消息推送涉及到服务端的消息发送、客户端的消息接收、通知渠道(... 目录一、项目概述二、相关知识介绍2.1 消息推送的基本原理2.2 Firebase Cloud Me

Linux中的计划任务(crontab)使用方式

《Linux中的计划任务(crontab)使用方式》:本文主要介绍Linux中的计划任务(crontab)使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、前言1、linux的起源与发展2、什么是计划任务(crontab)二、crontab基础1、cro

Linux换行符的使用方法详解

《Linux换行符的使用方法详解》本文介绍了Linux中常用的换行符LF及其在文件中的表示,展示了如何使用sed命令替换换行符,并列举了与换行符处理相关的Linux命令,通过代码讲解的非常详细,需要的... 目录简介检测文件中的换行符使用 cat -A 查看换行符使用 od -c 检查字符换行符格式转换将