您的位置:首页 > 运维架构 > Linux

[Linux] 进程通信-消息队列

2013-05-03 00:48 495 查看
/*
* =====================================================================================
*
*       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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: