/*
* =====================================================================================
*
* Filename: msq.c
*
* Description:
*
* Version: 1.0
* Created: 2013年05月03日 00时20分50秒
* Revision: none
* Compiler: gcc
*
* Author: linkscue (scue),
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/msg.h>
#include <sys/ipc.h>
#include <unistd.h>
struct msg_buf {
int mtype;
char data[255];
};
/*
* === FUNCTION ======================================================================
* Name: main
* Description:
* =====================================================================================
*/
int main ( int argc, char *argv[] )
{
key_t key;
int msgid;
int ret;
struct msg_buf msgbuf;
key=ftok("/tmp/msg", 'a'); /* file to key */
printf("key = [%x]\n",key);
msgid=msgget(key,IPC_CREAT|0666); /* get file key id */
if (msgid == -1) {
printf("create error\n");
return -1;
}
msgbuf.mtype = getpid(); /* use pid to type */
strncpy(msgbuf.data, "test hehe", sizeof(msgbuf.data));
printf("msgbuf.data is [%s]\n", msgbuf.data);
ret=msgsnd(msgid, &msgbuf, sizeof(msgbuf.data), IPC_NOWAIT); /* send */
if (ret == -1) {
printf("send message error\n");
return -1;
}
memset(&msgbuf, '\0', sizeof(msgbuf));
ret=msgrcv(msgid, &msgbuf, sizeof(msgbuf.data), msgbuf.mtype, IPC_NOWAIT ); /* receive */
if (ret==-1) {
printf("receive message error \n");
return -1;
}
printf("receive message is %s\n", msgbuf.data);
return EXIT_SUCCESS;
}