例程代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <time.h>
#define MSGFILE "./msgkey" //当前键值获取路径
struct msgbuf
{
long mtype; /* message type, must be > 0 */
char msgbuff[1024]; /* 存储发送消息buff */
}msg;
int main(int argc, const char *argv[])
{
int msgid = 0;
time_t tm;
int nCount = 0;
//键值为自动获取
key_t key;
key = ftok(MSGFILE,10);
printf("key:[%d].\n",key);
//创建队列并给出权限0666
msgid = msgget(key,IPC_CREAT | 0666);
if(msgid == -1)
{
perror("msgget");
}
//打印进程ID及消息队列ID
printf("pid:[%d]----msiid:[%d].\n",getpid(),msgid);
//循环发送或接收消息
while(1)
{
if(strncmp(argv[1],"recv",4) == 0)
{
//接收
if(msgrcv(msgid,&msg,1024,123,0) == -1)
{
perror("msgrcv");
}
printf("receive msg.mtype is:%ld, msg.msgbuff is: %s",msg.mtype, msg.msgbuff);
}
//发送
if(strncmp(argv[1],"send",4) == 0)
{
msg.mtype = 123;
time(&tm);
sprintf(msg.msgbuff,"CurTime[%d] : %s",nCount,ctime(&tm));
if(msgsnd(msgid,&msg,sizeof(msg.msgbuff),0) == -1)
{
perror("msgsnd");
}
printf("%s",msg.msgbuff);
}
nCount++;
sleep(1);
}
return 0;
}
效果如下: