Linux进程间通信-基于内存(共享队列)

来源:互联网 发布:买家怎么进淘宝试衣间 编辑:程序博客网 时间:2024/06/12 14:44

写在前面:小生纯业余选手,开此博仅仅是为了积累,纯当笔记来用。如有看官光临小生博客,请不要相信我的代码就是正确的。如果您发现了错误也恳请耽误您一点时间,请您在下面指出来,不胜感激!

如果发现一些笔记的说法完全是错误的请建议我删除!


使用共享队列机制实现进程间通信的过程
1.使用msgget创建共享队列/得到队列
2.使用msgsnd发送消息,使用msgrcv接收消息

3.使用msgctl删除队列


通过ipcs -q命令查看系统中的共享队列


代码中使用到struct msgbuf{};



这个结构体里边定义了一个char mtext[1]使用起来好像……

下面代码以这个结构体为模板自定义一个结构体

#include<unistd.h>#include<sys/ipc.h>#include<sys/msg.h>#include<stdio.h>#include<stdlib.h>#include<string.h>struct msgbuff{    long type;    char data[32];};int main(){    key_t key;    int msgid;        key = ftok(".",256);        if(key == -1)    {        printf("ftok error:%m\n");        exit(-1);    }        msgid = msgget(key,IPC_CREAT|IPC_EXCL|0666);        if(msgid == -1)    {        printf("error:%m\n");        exit(-1);    }        struct msgbuff msg;        for(int i = 1;i<=10;i++)    {        bzero(msg.data,sizeof(msg.data));        msg.type = 1;        sprintf(msg.data,"Message:%d",i);        msgsnd(msgid,&msg,sizeof(msg.data),0);    }        for(int i = 1;i<=10;i++)    {        bzero(msg.data,sizeof(msg.data));        msg.type = 2;        sprintf(msg.data,"Message:%d",i);        msgsnd(msgid,&msg,sizeof(msg.data),0);    }    return 0;} 
#include<unistd.h>#include<sys/ipc.h>#include<sys/msg.h>#include<stdio.h>#include<stdlib.h>#include<string.h>struct msgbuff{    long type;    char data[32];};int main(){    struct msgbuff msg;    key_t key = ftok(".",256);    if(key == -1)    {        printf("ftok error:%m\n");        exit(-1);    }        int msgid = msgget(key,0);    if(msgid == -1)    {        printf("get errpr:%m\n");        exit(-1);    }        while(1)    {        bzero(&msg,sizeof(msg));        msg.type = 2;        msgrcv(msgid,&msg,sizeof(msg.data),2,0);        printf("%s\n",msg.data);    }    return 0;}
第一段代码发送了两种类型的消息,第二段代码指定了接收到的消息的类型,所以只能接收显示相应类型的消息。


总结:

进程间通信机制虽然看完,但是很多函数的参数还要详细看man手册。总之,没那么简单,没那么复杂!

0 0
原创粉丝点击