简介
消息队列也是常见的进程通信方式之一,并且加上之后将要介绍的信号量和共享内存,这三种并称为XSI IPC。其特点可以参考这里(http://blog.youkuaiyun.com/wzhwho/article/details/3990118),但最终来自于APUE这本书。
示例
/*
* =====================================================================================
*
* Filename: my_msg.h
*
* Description: IPC using msg
*
* Version: 1.0
* Created: 2012年02月20日 11时10分28秒
* Revision: none
* Compiler: gcc
*
* Author: chn89 (), chn89@126.com
* Organization:
*
* =====================================================================================
*/
#ifndef __MY_MSG_H__
#define __MY_MSG_H__
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#define BUFSZ 256
#define MY_PATH "/home/canzhang/we"
#define MY_PATH_ID 4
struct mymsg_t{
long mtype;
char data[256];
};
#endif
/*
* =====================================================================================
*
* Filename: msg_ipc.c
*
* Description: IPC using msg
*
* Version: 1.0
* Created: 2012年02月20日 10时53分26秒
* Revision: none
* Compiler: gcc
*
* Author: chn (), chn89@126.com
* Organization:
*
* =====================================================================================
*/
#include "my_msg.h"
int main(void){
int msgid;
key_t my_key;
struct mymsg_t my_msg ;
long int rcv_num = 0;
my_key = ftok(MY_PATH, MY_PATH_ID);
msgid = msgget(my_key, 0666|IPC_CREAT);
if(msgid < 0){
printf("msgget error:%s with errno=0x%x",strerror(errno),errno);
exit(-1);
}
while(1){
if((msgrcv(msgid, (void*)&my_msg,BUFSZ,rcv_num,0))==-1){
printf("msgrcv error:%s with errno=0x%x",strerror(errno),errno);
exit(-1);
}
printf("receive data: %s\n",my_msg.data);
if(strncasecmp(my_msg.data,"q",1) == 0){
break;
}
}
if(msgctl(msgid, IPC_RMID,0)==-1){
printf("msgctl error:%s with errno=0x%x",strerror(errno),errno);
exit(-1);
}
return 0;
}
/*
* =====================================================================================
*
* Filename: msg_ipc_sender.c
*
* Description: IPC uisng msg sender
*
* Version: 1.0
* Created: 2012年02月20日 11时57分44秒
* Revision: none
* Compiler: gcc
*
* Author: chn (), chn89@126.com
* Organization:
*
* =====================================================================================
*/
#include "my_msg.h"
int main()
{
int msgid;
key_t my_key;
char buf[BUFSZ] = {0};
struct mymsg_t my_msg ;
my_msg.mtype = 2;
my_key = ftok(MY_PATH, MY_PATH_ID);
msgid = msgget(my_key, 0666|IPC_CREAT);
if(msgid < 0){
printf("msgget error:%s with errno=0x%x",strerror(errno),errno);
exit(-1);
}
while(1){
printf("input msg:\n");
fgets(buf, BUFSZ, stdin);
strncpy(my_msg.data, buf, BUFSZ);
my_msg.data[BUFSZ-1]='\0';
if(msgsnd(msgid, (void*)&my_msg, BUFSZ,0)==-1){
printf("msgsnd error:%s with errno=0x%x",strerror(errno),errno);
exit(-1);
}
if(strncasecmp(my_msg.data,"q",1)==0){
break;
}
}
return 0;
}
分别将两个c文件编译为两个可执行程序,即可实现进程消息队列通信。