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

Linux下进程通信之消息队列

2013-05-08 16:46 489 查看
read date from message: msg_r.c

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>

#define BUFFSIZE 2050

struct my_msg
{
long int l_msg_type;
char sz_msg_text[BUFFSIZE];
};

int main(void)
{
int n_run = 1;
int n_msgid;
struct my_msg st_msg;
long int l_rec_type;

n_msgid = msgget((key_t)1234,0666|IPC_CREAT);
if(n_msgid==-1)
{
fprintf(stderr,"create msg failed: %s!\n",strerror(errno));
exit(EXIT_FAILURE);
}

while(n_run)
{
if(msgrcv(n_msgid,(void*)&st_msg,BUFFSIZE,l_rec_type,0)==-1)
{
if(errno==EAGAIN)
{
printf("No data to read!\n");
sleep(1);
}
else
{
fprintf(stderr,"receive data error: %s !\n",strerror(errno));
exit(EXIT_FAILURE);
}
}
printf("You Write data: %s",st_msg.sz_msg_text);
if(strncmp(st_msg.sz_msg_text,"end",3)==0)
{
n_run=0;
}
}

if(msgctl(n_msgid,IPC_RMID,0)==-1)
{
fprintf(stderr,",remove msg failed:%s\n",strerror(errno));
exit(EXIT_FAILURE);
}

exit(EXIT_SUCCESS);
}

write data to messag: msg_w.c

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>

#define BUFFSIZE 1024
#define MAX_TEXT 2048

struct my_msg
{
long int l_msg_type;
char sz_msg_text[MAX_TEXT];
};

int main(void)
{
int n_run = 1;
int n_msgid;
struct my_msg st_msg;
long int l_rec_type;
char sz_buff[BUFFSIZE];

n_msgid = msgget((key_t)1234,0666|IPC_CREAT);
if(n_msgid==-1)
{
fprintf(stderr,"create msg failed: %s!\n",strerror(errno));
exit(EXIT_FAILURE);
}

while(n_run)
{
printf("please input data:");
fgets(sz_buff,BUFFSIZE,stdin);
st_msg.l_msg_type=1;
strcpy(st_msg.sz_msg_text,sz_buff);
//st_msg.sz_msg_text=sz_buff;
if(msgsnd(n_msgid,(void*)&st_msg,MAX_TEXT,0)==-1)
{
fprintf(stderr,"send data error: %s!\n",strerror(errno));
exit(EXIT_FAILURE);
}

if(strncmp(st_msg.sz_msg_text,"end",3)==0)
{
n_run=0;
}
}
exit(EXIT_SUCCESS);
}

msgsnd与msgrec在接受和发送数据类型要注意,不然变异很容易出错

1.传送的类型

2.传送和接收的数据空间
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: