信号队列

来源:互联网 发布:网络批发平台有哪些 编辑:程序博客网 时间:2024/05/18 20:06
  1. #include <sys/types.h>  
  2. #include <sys/msg.h>  
  3. #include <unistd.h>  
  4.   
  5. struct msg_buf  
  6.     {  
  7.         int mtype;  
  8.         char data[255];  
  9.     };  
  10.    
  11. int main()  
  12. {  
  13.         key_t key;  
  14.         int msgid;  
  15.         int ret;  
  16.         struct msg_buf msgbuf;  
  17.         struct msg_buf msgbuf1;  
  18.         struct msg_buf msgbuf2;  
  19.         struct msg_buf msgbuf3;  
  20.    
  21.         key=ftok("/tmp/2",'a');  
  22.         printf("key =[%x]\n",key);  
  23.         msgid=msgget(key,IPC_CREAT|0666); /*通过文件对应*/  
  24.   
  25.         if(msgid==-1)  
  26.         {  
  27.                 printf("create error\n");  
  28.                 return -1;  
  29.         }  
  30.    
  31.         msgbuf1.mtype = 1;  
  32.         strcpy(msgbuf1.data,"test haha1");  
  33.         msgbuf2.mtype = 2;  
  34.         strcpy(msgbuf2.data,"test haha2");  
  35.         msgbuf3.mtype = 3;  
  36.         strcpy(msgbuf3.data,"test haha3");  
  37.   
  38.         ret=msgsnd(msgid,&msgbuf1,sizeof(msgbuf1.data),IPC_NOWAIT);  
  39.         ret=msgsnd(msgid,&msgbuf2,sizeof(msgbuf2.data),IPC_NOWAIT);  
  40.         ret=msgsnd(msgid,&msgbuf3,sizeof(msgbuf3.data),IPC_NOWAIT);  
  41.         if(ret==-1)  
  42.         {  
  43.                 printf("send message err\n");  
  44.                 return -1;  
  45.         }  
  46.    
  47.         memset(&msgbuf,0,sizeof(msgbuf));  
  48.         ret=msgrcv(msgid,&msgbuf,sizeof(msgbuf.data),2,IPC_NOWAIT);  
  49.         if(ret==-1)  
  50.         {  
  51.                 printf("recv message err\n");  
  52.                 return -1;  
  53.         }  
  54.         printf("recv msg =[%s]\n",msgbuf.data);  
  55.    
  56. }  
0 0
原创粉丝点击