linux编程---进程通信---消息队列
来源:互联网 发布:全民推广源码 编辑:程序博客网 时间:2024/06/08 02:43
消息队列是消息的链式队列
1 创建消息队列
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget(key_t key, int msgflg);
2 消息队列属性控制
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
3 发送信息到消息队列
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
4 从消息队列接收信息
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
//msgtyp = 0 收到队列中第一条消息,任意类型
//msgtyp > 0 收到第一条msgtyp类型的消息
//msgtyp < 0 收到第一条最低类型(小于或等于msgtyp的绝对值)的消息。
struct msgbuf
{
long int mtype; /* type of received/sent message */
char mtext[1]; /* text of the message */
};
//mtype 是一个正整数,由产生消息的进程生成,用于表示消息的类型。
//mtext 是文本内容,即消息内容
简单实例
发送者代码
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<string.h>
#include<sys/msg.h>
#define BUFSIZE 128
struct msg_buf
{
long type;
char msg[BUFSIZE];
};
int main(int argc,char* argv[])
{
key_t key;
int msgid;
struct msg_buf msg_snd;
char buf[BUFSIZE];
if((key = ftok(".",'1')) == -1)
{
perror("ftok");
exit(-1);
}
if((msgid = msgget(key,0666|IPC_CREAT)) == -1)
{
perror("msgget");
exit(-1);
}
while(1)
{
printf("enter message to send:");
fgets(buf,BUFSIZE,stdin);
msg_snd.type = 1;
strcpy(msg_snd.msg,buf);
if((msgsnd(msgid,(void*)&msg_snd,BUFSIZE,0)) == -1)
{
perror("msgsnd");
exit(-1);
}
if(strncmp(buf,"end",3) == 0)
{
break;
}
}
return 0;
}
接收者代码
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<string.h>
#include<sys/msg.h>
#define BUFSIZE 128
struct msg_buf
{
long type;
char msg[BUFSIZE];
};
int main(int argc,char* argv[])
{
key_t key;
int msgid;
struct msg_buf msg_rcv;
int msg_to_rev = 0;
if((key = ftok(".",'1')) == -1)
{
perror("ftok");
exit(-1);
}
if((msgid = msgget(key,0666|IPC_CREAT)) == -1)
{
perror("msgget");
exit(-1);
}
while(1)
{
if((msgrcv(msgid,(void*)&msg_rcv,BUFSIZE,msg_to_rev,0)) == -1)
{
perror("msgrcv");
exit(-1);
}
printf("receiver message:%s",msg_rcv.msg);
if(strncmp(msg_rcv.msg,"end",3) == 0)
{
break;
}
}
if(msgctl(msgid,IPC_RMID,0) == -1)
{
perror("msgctl");
exit(-1);
}
return 0;
}
- Linux编程:进程间通信--消息队列
- linux编程---进程通信---消息队列
- linux消息队列进程通信
- linux消息队列进程通信
- linux消息队列进程通信
- linux进程通信---消息队列
- linux进程通信--消息队列
- linux进程通信--消息队列
- 【Linux】 进程通信--消息队列
- linux进程通信---消息队列
- linux进程通信-消息队列
- UNIX/LINUX编程学习之进程通信--消息队列
- Linux系统编程——进程间通信:消息队列
- Linux系统编程——进程间通信:消息队列
- 【Linux系统编程】进程间通信--消息队列
- Linux系统编程——进程间通信:消息队列
- 系统编程之进程通信 消息队列
- Linux进程间通信: 消息队列
- U-boot的工作流程分析-6410
- 敏捷开发的6个实战经验
- jeesite上传附件总是JS报错但不影响功能(已解决)
- SVN中与资源库同步时报告了错误。1 中的 0 个资源已经同步
- 哈唏连接
- linux编程---进程通信---消息队列
- python 去除txt文本中的空格、数字、特定字母等
- 包以及报文首部的简单理解
- Learning Bash 学习bash
- newInstance()
- 【图论】最短路径&&最小生成树问题
- Java单例模式
- Microbiome:HiSeq平台16S扩增子超高通量测序文库构建方法
- 《创业在路上》新媒体管家,玩转新媒体