//write.c #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> struct mymesg{ long mtype;//消息的类型,是一个整数且大于0 char mtex[512];//消息数据本身,是第三个参数的内容 }; int mian() { char *str = "hello world"; struct mymesg m1; m1.mtype = 100; memcpy(m1.mtex, str, sizeof(str)); key_t key = ftok("./", 0); //int msgget(key_t key, int msgflg) int msq_id = msgget(key, IPC_CREAT|IPC_EXCL|0777); if(msq_id < 0){ printf("create message queue failed\n"); return -1; } //ssize_t msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) if(msgsnd(msq_id, &m1, sizeof(struct mymesg)-sizeof(long), 0) < 0){ printf("send failed\n"); } return 0; }
//read.c #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> struct mymesg{ long mtype;//消息的类型,是一个整数且大于0 char mtex[512];//消息数据本身,是第三个参数的内容 }; int mian() {struct mymesg m1; m1.mtype = 100; key_t key = ftok("./", 0); //int msgget(key_t key, int msgflg) int msq_id = msgget(key, 0777); if(msq_id < 0){ printf("open message queue failed\n"); return -1; } //ssize_t msgrcv(int msgqid,void *ptr,size_t nbytes,long type,int flag) if(msgrcv(msq_id, m1.mtex, sizeof(struct mymesg) - sizeof(long), m1.mtype, 0) < 0){ printf("receive failed\n"); }else{
printf("mtex = %s\n",m1.mtex);
} return 0; }
标签:struct,队列,int,实例,m1,key,进程,include,id From: https://www.cnblogs.com/zj-studyrecoding/p/17266089.html