直接上代码吧。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdint.h>
#include<pthread.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<unistd.h>
#include<signal.h>
#include<errno.h>
#define MSG_KEY_TEST (1226)
typedef struct _tag_msg_buf
{
long mtype;
char buff[32];
}MSG_BUF_S;
int msgid=0;
pthread_mutex_t mutex;
void *fun_send(void *para)
{
MSG_BUF_S msgbuf;
int cnt=0;
printf("enter the [%s]\n",__FUNCTION__);
while(1)
{
//pthread_mutex_lock(&mutex);
memset(&msgbuf,0,sizeof(msgbuf));
msgbuf.mtype = 1;
msgbuf.buff[0]=cnt++;
msgsnd(msgid,&msgbuf,sizeof(msgbuf),0);
sleep(2);
}
return NULL;
}
void *fun_recv(void *para)
{
MSG_BUF_S msgbuf;
printf("enter the [%s]\n",__FUNCTION__);
while(1)
{
printf("i am ready for receive msg...\n");
memset(&msgbuf,0,sizeof(msgbuf));
msgrcv(msgid,&msgbuf,sizeof(msgbuf),1,0);
printf("receive done.\n");
printf("my recv data = %d\n",msgbuf.buff[0]);
}
return NULL;
}
static void exit_log(int signo)
{
switch(signo)
{
case SIGINT:
case SIGSEGV:
default:
printf("del the ipc-message queue id[%d]\n",msgid);
msgctl(msgid,IPC_RMID,NULL);
break;
}
exit(0);
}
int main(void)
{
pthread_t id_snd;
pthread_t id_rcv;
int ret=0;
signal(SIGINT,exit_log);
signal(SIGSEGV,exit_log);
msgid = msgget(MSG_KEY_TEST,IPC_CREAT|IPC_EXCL|0666);
if(msgid < 0)
{
if(EEXIST == errno)
{
printf("get the exist msgid...");
ret = msgget(MSG_KEY_TEST,IPC_CREAT|0666);
if(ret<0)
{
printf(" error:%d\n",ret);
return -1;
}
else
{
msgid = ret;
printf("the exist msgid = %d\n",msgid);
}
}
else
{
printf("msgget error\n");
return -1;
}
}
printf("get a ipc-message-queue id [%d].\n",msgid);
printf("creating fun_send and fun_recv...\n");
pthread_create(&id_snd,NULL,fun_send,NULL);
pthread_create(&id_rcv,NULL,fun_recv,NULL);
printf("create pthreads done.\n");
pthread_join(id_snd,NULL);
pthread_join(id_rcv,NULL);
printf("exit the test ptheads.\n");
return 0;
}
运行结果为:
[zhang@zwfedora23 testmsg]$ ./test
get the exist msgid...the exist msgid = 131072
get a ipc-message-queue id [131072].
creating fun_send and fun_recv...
create pthreads done.
enter the [fun_recv]
i am ready for receive msg...
enter the [fun_send]
receive done.
my recv data = 0
i am ready for receive msg...
receive done.
my recv data = 1
i am ready for receive msg...
receive done.
my recv data = 2
i am ready for receive msg...
receive done.
my recv data = 3
i am ready for receive msg...
receive done.
my recv data = 4
i am ready for receive msg...
^Cdel the ipc-message queue id[131072]
[zhang@zwfedora23 testmsg]$
1.当系统中存在要获取的msgid时,重新使用IPC_CREAT再获取一遍;
2.使用Ctrl+C退出系统时删除本次创建的IPC-Message-Queue;
3.msgrcv()使用阻塞方式获取信息,没有的消息的话就阻塞等着,一直到msgsnd发送了消息。