本文主要是介绍linuxIPC之消息队列,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
发送端
/*************************************************************************> File Name: msgsnd.c> Author: XXDK> Email: v.manstein@qq.com > Created Time: Mon 20 Mar 2017 12:24:01 AM PDT************************************************************************/#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/msg.h>
#include<errno.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>typedef struct msg{long mtype;int a;char c;
}msg_t;int main()
{int msgid;key_t key;msg_t mymsga;msg_t mymsgb;mymsga.mtype = 1;mymsga.a = 88;mymsga.c = 'a';mymsgb.mtype = 2;mymsgb.a = 99;mymsgb.c = 's';key = ftok("./.", 100);msgid = msgget(key, IPC_CREAT|IPC_EXCL|0666);if(msgid == -1) {if(errno == EEXIST) {msgid = msgget(key, 0666);} else {perror("fail to msgget");}}msgsnd(msgid, &mymsga, sizeof(mymsga) - sizeof(long), 0);msgsnd(msgid, &mymsgb, sizeof(mymsgb) - sizeof(long), 0);printf("send message ok\n");return 0;
}

/*************************************************************************> File Name: msgrcv.c> Author: XXDK> Email: v.manstein@qq.com > Created Time: Mon 20 Mar 2017 12:24:01 AM PDT************************************************************************/#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/msg.h>
#include<errno.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>typedef struct msg{long mtype;int a;char c;
}msg_t;int main()
{int msgid;key_t key;msg_t mymsg;key = ftok("./.", 100);msgid = msgget(key, IPC_CREAT|IPC_EXCL|0666);if(msgid == -1) {if(errno == EEXIST) {msgid = msgget(key, 0666);} else {perror("fail to msgget");}}system("ipcs -q");msgrcv(msgid, &mymsg, sizeof(mymsg) - sizeof(long), (long)1, 0);printf("mymsg: %d %c\n", mymsg.a, mymsg.c);system("ipcs -q");msgrcv(msgid, &mymsg, sizeof(mymsg) - sizeof(long), (long)2, 0);printf("mymsg: %d %c\n", mymsg.a, mymsg.c);system("ipcs -q");msgctl(msgid, IPC_RMID, NULL);return 0;
}
这篇关于linuxIPC之消息队列的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!