Linux下的消息队列的使用

xiaoxiao2021-02-28  16

消息队列是一种可以一对多的传输信号的方式

#include<stdio.h>

#include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> #include<string.h> #include<stdlib.h> struct msgbuf { long mtype; char mtext[1024]; }; int main() { char buffer[1024] = {0}; key_t key = ftok(".", 2);                                            //将文件名转化为键值 if (-1 == key)                        { perror("key"); } int msgid = msgget(key, IPC_CREAT);                       //创建消息队列 if (msgid == -1) { perror("msgget"); } while(1) { struct msgbuf buf; scanf("%d %s", &buf.mtype, buf.mtext); msgsnd(msgid, &buf, sizeof(buf.mtext), 0);                //发送信息给消息队列 memset(buf.mtext, 0, 1024);                                    } return 0;

}

-----------------------------------------分割线--------------------------------------------------

#include<stdio.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/msg.h> #include<string.h> #include<stdlib.h> struct msgbuf { long mtype; char mtext[1024]; }; int main() { key_t key = ftok(".", 2);                                             if (-1 == key) { perror("key"); } int msgid = msgget(key, IPC_CREAT); if (msgid == -1) { perror("msgget"); } int type; scanf("%d", &type); while(1) { struct msgbuf buf; msgrcv(msgid, &buf, sizeof(buf.mtext), type, 0);               //接受信号,其中type为接受的信号编码 printf("rcv = %s\n", buf.mtext); } return 0; }

转载请注明原文地址: https://www.6miu.com/read-200005.html

最新回复(0)