#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
参数:
msqid:消息队列的标识(区别其他消息队列)
msgp参数是指向以下一般形式的调用者定义的结构:
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[xxx]; /* message data */
};
msgsz: 消息队列大小
(备注:msgsz大小与mtext大小相等),
一般形式: msgsz=sizeof(struct msgbuf) - sizeof(long);
msgflg:为以下选项
IPC_NOWAIT:立即返回,如果没有请求类型的消息在队列中。
MSG_EXCEPT:与msgtyp大于0用于在队列中与从msgtyp不同消息类型读取所述第一消息。
MSG_NOERROR:如果大于msgsz字节数进行截断。
返回值:失败返回-1,成功msgsnd返回0、msgrcv返回接受mtext数据字节大小
注:msgp结构体中mtype与msgrcv中参数msgtyp对应的。
发送端代码:msgrcv.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <time.h>
#define TEXT_SIZE 512
struct msgbuf
{
long mtype ;
int status ;
char time[20] ;
char mtext[TEXT_SIZE] ;
} ;
char *getxtsj()
{
time_t tv ;
struct tm *tmp ;
static char buf[20] ;
tv = time( 0 ) ;
tmp = localtime(&tv) ;
sprintf(buf,"%02d:%02d:%02d",tmp->tm_hour , tmp->tm_min,tmp->tm_sec);
return buf ;
}
int main(int argc, char **argv)
{
int msqid ;
struct msqid_ds info ;
struct msgbuf buf ;
struct msgbuf buf1 ;
int flag ;
int sendlength, recvlength ;
int key ;
key = ftok("msg.tmp", 0x01 ) ;
if ( key < 0 )
{
perror("ftok key error") ;
return -1 ;
}
msqid = msgget( key, 0600|IPC_CREAT ) ;
if ( msqid < 0 )
{
perror("create message queue error") ;
return -1 ;
}
buf.mtype = 1 ;
buf.status = 9 ;
strcpy(buf.time, getxtsj()) ;
strcpy(buf.mtext, "happy new year!") ;
sendlength = sizeof(struct msgbuf) - sizeof(long) ;
flag = msgsnd( msqid, &buf, sendlength , 0 ) ;
if ( flag < 0 )
{
perror("send message error") ;
return -1 ;
}
buf.mtype = 3 ;
buf.status = 9 ;
strcpy(buf.time, getxtsj()) ;
strcpy(buf.mtext, "good bye!") ;
sendlength = sizeof(struct msgbuf) - sizeof(long) ;
flag = msgsnd( msqid, &buf, sendlength , 0 ) ;
if ( flag < 0 )
{
perror("send message error") ;
return -1 ;
}
system("ipcs -q") ;
return 0 ;
}
接受端代码:msgsnd.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define TEXT_SIZE 512
struct msgbuf
{
long mtype ;
int status ;
char time[20] ;
char mtext[TEXT_SIZE] ;
} ;
int main(int argc, char **argv)
{
int msqid ;
struct msqid_ds info ;
struct msgbuf buf1 ;
int flag ;
int recvlength ;
int key ;
int mtype ;
key = ftok("msg.tmp", 0x01 ) ;
if ( key < 0 )
{
perror("ftok key error") ;
return -1 ;
}
msqid = msgget( key, 0 ) ;
if ( msqid < 0 )
{
perror("get ipc_id error") ;
return -1 ;
}
recvlength = sizeof(struct msgbuf) - sizeof(long) ;
memset(&buf1, 0x00, sizeof(struct msgbuf)) ;
mtype = 1 ;
flag = msgrcv( msqid, &buf1, recvlength ,mtype,0 ) ;
if ( flag < 0 )
{
perror("recv message error\n") ;
return -1 ;
}
printf("type=%d,time=%s, message=%s\n", buf1.mtype, buf1.time, buf1.mtext) ;
system("ipcs -q") ;
return 0 ;
}
详情可参考以下博客:http://blog.csdn.net/guoping16/article/details/6584024