您的位置:首页 > 其它

进程间消息队列通信

2012-05-21 20:03 260 查看
要保证server能够接收client的消息,就必须保证server的生成的msg的标识符是一样的,也就是两个用的key是必须一样的。

msgLucy.c

#include<sys/ipc.h>

#include<sys/msg.h>

#include<sys/stat.h>

#include<sys/types.h>

#include<stdio.h>

#include<fcntl.h>

#include<signal.h>

#include<stdlib.h>

#include<string.h>

#define PROJID 0XFF

#define LUCY 1

#define PETER 2

#define SEED 'g'

int mqid;

void terminate_handler(int );

void terminate_handler(int signo)

{

msgctl(mqid,IPC_RMID,NULL);/*delete the data*/

exit(0);

}

int main()

{

//char filenm[]="msg";

key_t mqkey;

struct msgbuf

{

long mtype;

char mtext[256];

int * m;

}msg;

int ret;

mqkey = ftok(".",SEED);/*get the same key*/

if(mqkey==-1)

{

perror("ftok error:");

exit(-1);

}

mqid = msgget(mqkey,IPC_CREAT|0666);/*if not creat or open it*/

if(mqid==-1)

{

perror("msgget error:");

exit(-1);

}

signal(SIGINT,terminate_handler);

signal(SIGTERM,terminate_handler);

while(1)

{

printf("Lucy:");

fgets(msg.mtext,256,stdin);

if(strncmp("quit",msg.mtext,4)==0)

{

msgctl(mqid,IPC_RMID,NULL);

exit(0);

}

//printf("IPC_NOWAIT=%d\n",IPC_NOWAIT);

msg.mtext[strlen(msg.mtext)-1] = '\0';

msg.mtype = LUCY;

msgsnd(mqid,&msg,strlen(msg.mtext)+1,0);/*block method*/

msgrcv(mqid,&msg,sizeof(struct msgbuf),PETER,0);/*can recieve the address*/

printf("Peter:%s\n",msg.mtext);

printf("the ponit m:%p\n",msg.m);

}

}

msgPeter.c

#include<sys/ipc.h>

#include<sys/msg.h>

#include<sys/stat.h>

#include<sys/types.h>

#include<stdio.h>

#include<fcntl.h>

#include<signal.h>

#include<stdlib.h>

#include<string.h>

#define PROJID 0XFF

#define LUCY 1

#define PETER 2

#define SEED 'g'

void terminate_handler(int );

int mqid;

void terminate_handler(int signo)

{

msgctl(mqid,IPC_RMID,NULL);

exit(0);

}

int main()

{

//char filenm[]="msg";

//int mqid;

key_t mqkey;

int n;

struct msgbuf

{

long mtype;

char mtext[256];

int * m;

}msg;

int ret;

mqkey = ftok(".",SEED);

if(mqkey==-1)

{

perror("ftok error:");

exit(-1);

}

if((mqid = msgget(mqkey,0))==-1)

{

printf("come here!!!!!!!!!!!!!!\n");/*if not creat and come here or open it*/

mqid = msgget(mqkey,IPC_CREAT|0666);

}

//mqid = msgget(mqkey,0);

if(mqid==-1)

{

perror("msgget error:");

exit(-1);

}

n=4;

msg.m=&n;

printf("the ponit m:%p\n",msg.m);

printf("msg.m's value is %d\n",*(msg.m));

signal(SIGINT,terminate_handler);

signal(SIGTERM,terminate_handler);

while(1)

{

msgrcv(mqid,&msg,sizeof(struct msgbuf),LUCY,0);

printf("LUCY:%s\n",msg.mtext);

printf("Peter:");

fgets(msg.mtext,256,stdin);

if(strncmp("quit",msg.mtext,4)==0)

{

msgctl(mqid,IPC_RMID,NULL);

exit(0);

}

msg.mtext[strlen(msg.mtext)-1] = '\0';

msg.mtype = PETER;

msgsnd(mqid,&msg,sizeof(struct msgbuf),0);/*can send the address to the server*/

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: