一、共享内存
共享内存是通信效率最高的进程间通信方3式——内存映射(将内核空间地址映射到用户空间,访问该映射空间即相当于访问内核空间)
二、消息队列
就是一些消息的列表。比FIFO具有更大的优势,可以选择性的接受某些消息。
指令 ipcs 查看系统的IPC对象
三、主要函数
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>
/*获取key值*/
key_t ftok(const char *pathname, int proj_id);
/*创建共享内存*/
int shmget(key_t key, size_t size, int shmflg);
shmget()返回与参数键的值关联的System V共享内存段的标识符。如果key的值为IPC_PRIVATE或key的值不是IPC_PRIVATE,不存在与key对应的共享内存段,并且在shmflg中指定了IPC_create,则会创建一个新的共享内存段,其大小等于size的值,取整为PAGE_size的倍数。
如果shmflg同时指定IPC_CREAT和IPC_EXCL,并且密钥的共享内存段已经存在,则shmget()将失败,errno设置为EEXIST。(这类似于组合O|u CREAT | O|u EXCL对open(2)的效果。)
/*内存映射*/
void *shmat(int shmid, const void *shmaddr, int shmflg);
* If shmaddr is NULL, the system chooses a suitable (unused) address at which to attach the segment.
shmflg: SHM_EXEC SHM_RDONLY SHM_REMAP
/*取消映射*/
int shmdt(const void *shmaddr);
/*关闭共享内存*/
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
cmd: IPC_RMID
buf: NULL
/*创建消息队列*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget(key_t key, int msgflg);
If msgflg specifies both IPC_CREAT and IPC_EXCL and a message queue already exists for key, then msgget() fails with errno set to EEXIST. (This is analogous to the effect of the combination O_CREAT | O_EXCL for open(2).)
/*发送与接受消息*/
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);
msqid是msgget返回值
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[1]; /* message data */
};
msgsz为struct msgbuf中mtext的大小,即正文大小。通过mtype达到有选择性的接受数据
msgflg常用选项:IPC_NOWAIT MSG_COPY MSG_EXCEPT
msgtyp:选择接受的消息类型,即结构体中的第一个元素
/*关闭消息队列*/
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
cmd:IPC_RMID ——