天天看點

消息隊列示例

消息隊列是将消息按隊列的方式組織成的連結清單,每個消息都是其中的一個節點。

消息隊列的操作函數有一下幾個:

int  msgget(key_t key, int msgflg)    //建立1個消息隊列

int  msgsnd(int msqid, const void *msgptr, int msgsz , int msgflg)  //發送消息到消息隊列中

int  msgrcv (int msqid,void *msgptr, int msgsz ,long msgtyp, int msgflag) //從消息隊列中讀取一個消息

int msgctl (int msqid, int cmd ,struct msqid_ds *buf)  //消息隊列控制函數

示例如下:

#include <string.h>

#include <sys/types.h>

#include <sys/msg.h>

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>

int main(void)

{

int msg_id,msg_flags;   

int reval;

char send_msg[64];

msg_flags = IPC_CREAT | 0666;  

msg_id = msgget((key_t)456,msg_flags);  //建立消息隊列并傳回消息隊列id

if(-1 == msg_id)        //判斷是否建立成功(傳回-1 為失敗)

{

printf("msg create error.\n");

exit(EXIT_FAILURE);

}

memset(send_msg,0,64); 

sprintf(send_msg,"hi, I'm %d.\n",getpid()); // 列印字元串到send_msg 中

reval = msgsnd(msg_id,send_msg,sizeof(send_msg),0);//将send_msg中的消息發送到消息隊列中,消息隊列的id為msg_id

if(-1 == reval)  //發送消息失敗傳回-1

{

printf("message send error.\n");

exit(EXIT_FAILURE);

}

else

printf("Send message:%s\n",send_msg);  

return 0;

}

#include <string.h>

#include <sys/types.h>

#include <sys/msg.h>

#include <unistd.h>

#include <stdlib.h>

#include <stdio.h>

int main(void)

{

int msg_id,msg_flags;   

int reval;

char send_msg[64];

msg_flags = IPC_CREAT | 0666;  

msg_id = msgget((key_t)456,msg_flags);

if(-1 == msg_id)        //判斷是否建立成功(傳回-1 為失敗)

{

printf("msg create error.\n");

exit(EXIT_FAILURE);

}

memset(send_msg,0,64); 

reval = msgrcv(msg_id,send_msg,64,0,0);//從消息隊列中讀取一個消息

if(-1 == reval)  //發送消息失敗傳回-1

{

printf("message send error.\n");

exit(EXIT_FAILURE);

}

else

printf("Received message:%s\n",send_msg); 

reval = msgctl(msg_id,IPC_RMID,0);

if(-1 == reval)

{

printf("remove msg queue error\n");

exit(EXIT_FAILURE);

}

return 0;

}

繼續閱讀