system v 消息队列

来源:互联网 发布:黑色星期天 知乎 编辑:程序博客网 时间:2024/04/29 14:05

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

#include <stdio.h>#include <string.h>#include <stdlib.h> struct mmsg{ long msgtype;    char msgtext[64];};

#include "mymsg.h"#if 0#include <sys/types.h>#include <sys/ipc.h>#include <sys/msg.h>#include <unistd.h>#include <stdio.h>#include <string.h>#include <stdlib.h>struct mmsg{long msgtype;char msgtext[64];};#endifint main(){int   qid;key_t key;int   len;int   ret;    int i;    struct mmsg msgbuf;//struct message msg;   if((key=ftok("/home/luguangxu/loader.c",'a'))==-1){perror("ftok");    exit(1);}if((qid=msgget(key,IPC_CREAT|0666))==-1){    //¡ä?¡§???¡é®D  27.     perror("msgget");    exit(1);}printf("opened queue %d\n",qid);printf("sizeof(long)== %d bytes\n",(int)sizeof(long));i=1;len = sizeof(struct mmsg) - sizeof(long);printf("===%d\n",len);while(1){msgbuf.msgtype = i;memset(msgbuf.msgtext, 0, sizeof(msgbuf.msgtext));sprintf(msgbuf.msgtext,"hello,text==%d.",i);    if( msgsnd(qid, &msgbuf, len, 0) < 0 ){perror("msgsnd ");break;}    i++;sleep(1);}return 0;}

#include "mymsg.h"

#if 0

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

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h> 

struct msg{             long msgtype;      char msgtext[64];  }; 

#endif typedef struct mmsg mm;int main(){ int   qid; key_t key;    int   len; int   ret; //struct mmsg buf; mm buf; //if( (key = ftok("/home/luguangxu/mm", 'a')) == -1) if( (key = ftok("/home/luguangxu/loader.c", 'a')) == -1) {  perror("ftok");  return -1; } if((qid = msgget(key, 0666)) == -1 ) {  perror("msgget");  return -1; } printf("opened queue %d\n",qid); printf("sizeof(long) == %d bytes...\n",(int)sizeof(long));

 while(1) {  memset(&buf, 0, sizeof(buf));#if 0  // 判断有没有特定类型的消息,却不读取  if( (ret = msgrcv(qid, NULL, 0,5,IPC_NOWAIT)) < 0 )  {   if( errno == E2BIG )   {    printf(" 1111111111111 \n");   }   else   {    printf(" 222222222222  \n");   }  }#endif  if( (ret = msgrcv(qid, &buf, sizeof(struct mmsg) - sizeof(long), 0, 0)) < 0 )     {   perror("msgrcv");   exit(1);  }        printf("buf.msgtype == %ld...  buf.msgtext ==%s...ret == %d ,strlen(buf.msgext) == %d \n",buf.msgtype,buf.msgtext, ret , (int) strlen(buf.msgtext));     //sleep(1); } return 0;}


原创粉丝点击