消息队列

    科技2022-07-10  98

    #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h>

    int msgget(key_t key, int msgflg);                                                      // 创建打开消息队列

     int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);  //添加消息(写入)

     ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,  //读取消息

                              int msgflg);

    int msgctl(int msqid, int cmd, struct msqid_ds *buf);                      // 控制消息队列 

     msgctl一般用来释放消息队列中的内容:

     msgctl(msgid,IPC_RMID,NULL);

    ftok函数:

    key_t ftok(const char *pathname, int proj_id);

    key_t key;

    key = ftok(".",1);   //" . "表示当前文件

    //  1 :id值,只能使用8bits(1-125)

     

     消息队列通信原理:

    消息队列是消息的链表,存放在内核中。一个消息队列由一个表示符(即队列ID)来标识。//消息队列以链表存储,所以其中每个消息都为结构体类型。

     

    消息队列读取操作:

    #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <string.h>

    //ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,   //                    int msgflg);

    struct msgbuf {         long mtype;       // 消息队列类型         char mtext[128];    // 内容 };

    int main() {         struct msgbuf readbuf;

            int msgid = msgget(0x1234, IPC_CREAT|0777); // IPC_CREAT:当未找到相对应的key值时创建新的队列

            if(msgid == -1){                 printf("creat is fail\n");         }

            msgrcv(msgid,&readbuf,sizeof(readbuf.mtext),888,0); // 888:队列类型。

                                 //读取时必须用 sizeof 函数,因为readbuf.mtext中没有内容。         printf("read form que :%s\n",readbuf.mtext);

            struct msgbuf sendbuf = {988,"this is from read sososo"};                                               // 988: 消息队列类型。"this is from read sososo":内容。

            msgsnd(msgid,&sendbuf,strlen(sendbuf.mtext),0);

            return 0; }  

                         

     消息队列写入操作:

    include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <string.h>

    // int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);

    struct msgbuf {         long mtype;       /* message type, must be > 0 */         char mtext[128];    /* message data */ };

    int main() {         struct msgbuf sendbuf = {888,"this is from send"};

            int msgid = msgget(0x1234, IPC_CREAT|0777);

            if(msgid == -1){                 printf("creat is fail\n");         }

            msgsnd(msgid,&sendbuf,strlen(sendbuf.mtext),0);

            struct msgbuf readbuf;

            msgrcv(msgid,&readbuf,sizeof(readbuf.mtext),988,0);         printf("read form que :%s\n",readbuf.mtext);

            return 0; }  

    Processed: 0.024, SQL: 8