消息队列
#include <myhead.h>
//消息结构体
typedef struct
{long msgtype; //消息类型char data[1024]; //消息正文
}Msg_ds; #define SIZE sizeof(Msg_ds)-sizeof(long) //正文大小int main(int argc, const char *argv[])
{//1、创建key值key_t key;if((key = ftok("/", 'k')) == -1){perror("ftok error");return -1;}//2、创建消息队列int msgid; if((msgid = msgget(key, IPC_CREAT|0664)) == -1){perror("msgget error");return -1;}//3、向消息队列中发送数据Msg_ds msg = {.msgtype = 100};while(1){printf("请输入消息内容:");fgets(msg.data, sizeof(msg.data), stdin); //从终端输入字符串//将字符串的'\n'换成'\0'msg.data[strlen(msg.data)-1] = '\0';//将消息发送到消息队列中if(msgsnd(msgid, &msg, SIZE, 0) == -1){perror("msgsnd error");return -1;}if(strcmp(msg.data, "quit") == 0){break;} }return 0;
}
#include <myhead.h>
#define ERR_MSG(msg) do{\
fprintf(stderr,"__%d__:",__LINE__);\
perror(msg);\
}while(0)//消息结构体
typedef struct
{long msgtype; //消息类型char data[1024]; //消息正文
}Msg_ds;#define SIZE sizeof(Msg_ds)-sizeof(long) //正文大小int main(int argc, const char *argv[])
{//1、创建key值key_t key;if((key = ftok("/", 'k')) == -1){ERR_MSG("ftok");return -1;}//2、创建消息队列int msqid;if((msqid = msgget(key,IPC_CREAT|0664)) == -1){ERR_MSG("msgget");return -1;}//3、从消息队列中读取数据Msg_ds msg;while(1){if(msgrcv(msqid,&msg,SIZE,0,0)==-1){ERR_MSG("msgrcv");return -1;}if(strcmp(msg.data,"quit")==0){break;}printf("rcv:%s\n",msg.data);}msgctl(msqid,IPC_RMID,NULL);return 0;
}