linux-使用私有消息队列

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;
}
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值