消息队列学习小结

来源:岁月联盟 编辑:exp 时间:2012-09-02
[cpp]
//  ipcs -q -i 0 
//  Semaphore Arrays 
//  Shared Memory Segments 
//  Messages Queues 
 
#include<sys/ipc.h> 
#include<string.h> 
#include<unistd.h> 
#include<sys/types.h> 
#include<sys/msg.h> 
#include<stdio.h> 
#include<stdlib.h> 
#include<errno.h> 
 
struct msgbuf { 
  long mtype; 
  char mtext[100]; 
}; 
 
int main() 

  key_t key; 
  int msgid; 
  struct msgbuf msg1,msg2,msg3,msg4; 
  key=ftok("/home/web",'a'); 
  if ((msgid=msgget(key,IPC_CREAT|0666))<0) { 
    printf("msg err/n"); 
    printf("%s/n",strerror(errno)); 
    exit(-1); 
  } 
  printf("please input your name:/n"); 
  msg1.mtype=1; 
  strcpy(msg1.mtext,"text1"); 
  msg3.mtype=3; 
  strcpy(msg3.mtext,"text3"); 
  msg4.mtype=4; 
  strcpy(msg4.mtext,"text4"); 
 
//  msgsnd(msgid,&msg1,sizeof(msg1.mtext),0); 
//  msgsnd(msgid,&msg3,sizeof(msg3.mtext),0); 
//  msgsnd(msgid,&msg4,sizeof(msg4.mtext),0); 
 
  msgrcv(msgid,&msg2,100,4,0); 
  printf("---%s/n",msg2.mtext); 
  return 0;