总结下别人比较好的博文+自己写的一个栗子
1.ftok()
https://blog.csdn.net/u013485792/article/details/50764224
2.msgget,msgctl,msgsnd,msgrcv函数
https://blog.csdn.net/guoping16/article/details/6584024
3.一个栗子
/*************************************************************************
> File Name: show.c
> Author:
> Mail:
> Created Time: Wed 24 Oct 2018 12:28:25 PM UTC
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/msg.h>
#include<unistd.h>
#include<time.h>
#include<sys/ipc.h>
#include<errno.h>
void msg_show(int msg_id, struct msqid_ds msg_info) {
int ret = -1;
sleep(1);
ret = msgctl(msg_id, IPC_STAT, &msg_info);
if(-1 == ret) {
printf("消息获取失败\n");
perror("error");
return;
}
printf("\n队列中字节数:%ld\n",msg_info.msg_cbytes);
printf("队列中消息数:%d\n",(int)msg_info.msg_qnum);
printf("队列中的最大字节数:%d\n",(int)msg_info.msg_qbytes);
printf("最后发送消息的进程:%d\n",msg_info.msg_lspid);
printf("最后接受消息的进程:%d\n",msg_info.msg_lrpid);
printf("最后发送消息的时间:%s",ctime(&(msg_info.msg_stime)));
printf("最后接受消息的时间:%s",ctime(&(msg_info.msg_rtime)));
printf("最后变化的时间:%s",ctime(&(msg_info.msg_ctime)));
printf("消息UID:%d\n",msg_info.msg_perm.uid);
printf("消息GID:%d\n\n",msg_info.msg_perm.gid);
}
int main() {
int ret = -1;
int msg_flags,msg_id;
key_t key;
struct msgmbuf {
long mtype;
char mtext[10];
};
struct msqid_ds msg_info;
struct msgmbuf msg_mbuf;
msg_mbuf.mtype = 10;
int msg_sflags,msg_rflags;
char *msgpath = "/home/whiskey/study/进程/msgque";
key = ftok(msgpath, 'b');
if(-1 != key) {
printf("成功建立KEY\n");
}
else {
printf("建立KEY失败\n");
perror("error:");
}
msg_flags = IPC_CREAT|IPC_EXCL;
msg_id = msgget(key, msg_flags|0x0666);
if(-1 == msg_id) {
printf("消息建立失败\n");
return 0;
}
else {
printf("消息建立成功\n");
}
msg_show(msg_id, msg_info);
msg_sflags = IPC_NOWAIT;
memcpy(msg_mbuf.mtext, "123", sizeof("123"));
ret = msgsnd(msg_id, &msg_mbuf, sizeof("123"), msg_flags);
if(-1 == ret) {
perror("发送消息失败:");
}
msg_show(msg_id, msg_info);
msg_rflags = IPC_NOWAIT|MSG_NOERROR;
ret = msgrcv(msg_id, &msg_mbuf, 10, 10, msg_rflags);
if(-1 == ret) {
perror("接收消息失败:");
}
else {
printf("接受消息成功,长度:%d\n",ret);
}
msg_show(msg_id, msg_info);
msg_info.msg_perm.uid = 8;
msg_info.msg_perm.gid = 8;
msg_info.msg_qbytes = 12345;
ret = msgctl(msg_id, IPC_SET, &msg_info);
if(-1 == ret) {
perror("设置消息属性失败:");
return 0;
}
msg_show(msg_id, msg_info);
ret = msgctl(msg_id, IPC_RMID, NULL);
if(-1 == ret) {
perror("删除失败:");
return 0;
}
return 0;
}
运行时需要root权限,记得加sudo
编译时曾遇到的错误:
msgecv函数No message of desired type
原因:msgmbuf中mtype开始时我设置的是int类型,应该是long类型