deepfuture@deepfuture-laptop:~/private/mytest$ gcc -o testmes testmes.c
testmes.c: In function ‘main’:
testmes.c:18: warning: incompatible implicit declaration of built-in function ‘exit’
testmes.c:22: warning: incompatible implicit declaration of built-in function ‘malloc’
testmes.c:24: warning: incompatible implicit declaration of built-in function ‘strcpy’
testmes.c:32: warning: incompatible implicit declaration of built-in function ‘exit’
testmes.c:34: warning: incompatible implicit declaration of built-in function ‘free’
testmes.c:45: warning: incompatible implicit declaration of built-in function ‘exit’
deepfuture@deepfuture-laptop:~/private/mytest$ ./testmes
message 32769 queue created!
message send
recv:deepfuture.iteye.com
deepfuture@deepfuture-laptop:~/private/mytest$
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
int main(void){
int queue_id;
struct msgbuf *msg;
struct msgbuf *recv_msg;
int rc;
//建立消息队列
queue_id=msgget(IPC_PRIVATE,IPC_CREAT|0600);//IPC_PRIVATE表示私有消息队列,正整数表示公共的消息队列
if (queue_id==-1){
perror("create queue error!\n");
exit(1);
}
printf("message %d queue created!\n",queue_id);
//创建发送消息结构
msg=(struct msgbuf*)malloc(sizeof(struct msgbuf)+100);//100为消息的长度,msgbuf结构只有2个成员一个成员是mytpe,另一个成员是一个字节的mtext,在结构后分配更多的空间以存放消息字符串
msg->mtype=1;//消息类型,正整数
strcpy(msg->mtext,"deepfuture.iteye.com");
//发送消息
rc=msgsnd(queue_id,msg,100,0);
//最后一个参数可以是是0与随后这些值(或者就是0):IPC_NOWAIT,如果消息类型没有则立即返回,函数调用失败
//MSG_EXCEPT,当消息类型大于0时,读与消息类型不同的第一条消息
//MSG_NOERROR,如果消息长度大于100字节则被截掉
if (rc==-1){
perror("msgsnd error\n");
exit(1);
}
free(msg);//发送完毕,释放内存
printf("message send\n");
recv_msg=(struct msgbuf*)malloc(sizeof(struct msgbuf)+100);
rc=msgrcv(queue_id,recv_msg,101,0,0);//接收消息,倒数第二个参数是消息的类型,0表示消息队列中的第一条消息
//正整数表示对应的消息队列中的消息,负整数表示消息队列中的小于或等于该值的绝对值的消息中的第一条消息。
//最后一个参数可以是0与随后这些值(或者就是0):IPC_NOWAIT,如果消息类型没有则立即返回,函数调用失败
//MSG_EXCEPT,当消息类型大于0时,读与消息类型不同的第一条消息
//MSG_NOERROR,如果消息长度大于100字节则被截掉
if (rc==-1){
perror("recv error\n");
exit(1);
}
printf("recv:%s\n",recv_msg->mtext);
return 0;
}
本文介绍了一个使用消息队列进行通信的简单程序实例。通过创建消息队列、发送和接收消息的过程,展示了如何利用消息队列实现进程间通信。

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



