創建/打開消息隊列 msgget
發送數據 msgsnd
從消息隊列取消息 msgrcv
刪除消息隊列 msgctl
例如A進程代碼
#include
#include
#include
#include
#include
#include
struct msgt
{
long msgtype;
char msgtext[1024];
};
void main()
{
int msqid;
int msg_type;
char str[256];
struct msgt msgs;
//創建消息隊列
msqid = msgget(1025, IPC_CREAT);
//循環
while(1)
{
printf("please input message type, 0 for quit!\n");
//獲取消息類型
scanf("%d", &msg_type);
//如果用戶輸入的消息爲0,則退出
if(msg_type == 0)
break;
printf("please input message data!\n");
//獲取消息數據
scanf("%s", str);
msgs.msgtype = msg_type;
strcpy(msgs.msgtext, str);
//發送消息
msgsnd(msqid, &msgs, sizeof(struct msgt), 0);
}
//刪除消息隊列
msgctl(msqid, IPC_RMID, 0);
}
B進程代碼
#include
#include
#include
#include
#include
#include
int msqid;
struct msgt
{
long msgtype;
char msgtext[1024];
};
void myprocess()
{
struct msgt ms;
int x;
x = msgrcv(msqid, &ms, sizeof(struct msgt), 0, 0);
printf("the receive text: %s %d\n", ms.msgtext, x);
}
void main()
{
int i;
int cpid;
//打開消息隊列
msqid = msgget(1025, IPC_EXCL);
printf("the msqid is %d\n", msqid);
myprocess();
}