消息队列

来源:互联网 发布:淘宝医药网 编辑:程序博客网 时间:2024/06/06 20:11
消息队列,写进程
#include <iostream>
#include <sys/msg.h>
using namespace std;


int main(int argc, char* argv[])
{
    if(argc == 1)
    {
cout<<"give the msgque a key"<<endl;
return 0;
    }
    int key = atoi(argv[1]);


    int qid = msgget(key, IPC_CREAT|0600);
    if(qid < 0)
    {
cout<<"create msgque fail"<<endl;
return -1;
    }
    else
    {
cout<<"create ok"<<endl;
cout<<"key=0x"<<hex<<key<<endl;
cout<<"qid="<<qid<<endl;
    }


    struct Msg
    {
long channel;
char name[20];
    };
    Msg m;
    cout<<"input channel and name:";
    cin>>m.channel>>m.name;


    msgsnd(qid, &m, sizeof(m), 0);


}


写进程
#include <iostream>
#include <sys/msg.h>
using namespace std;


int main(int argc, char* argv[])
{
    int key = atoi(argv[1]);
    int qid = msgget(key, IPC_CREAT|0600);


    struct Msg
    {
long channel;
char name[20];
    };
    Msg m;


    int no;
    cout<<"input no to accept msg"<<endl;
    cin>>no;


    msgrcv(qid, &m, sizeof(m), no, 0);
    cout<<m.channel<<endl<<m.name<<endl;
}