消息队列的简单使用
根据客户端进程向消息队列中添加数据,服务端来根据客户端的进程id来判断是哪个进程,并且向指定的进程中回复指定的数据
- 客户端代码
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>
struct sen_usg{
long mtype;
pid_t cpid;
char msg[500];
};
struct send{
long mytype;
char input[256];
};
int main( void )
{
int msgid,ret,pid,key,key1,msgid1;
struct sen_usg snd_msg;
struct send send_p;
pid = getpid();
key = ftok( "/tmp", 0 );
key1= ftok( "/tmp", 9 );
if((key<0)||(key1<0))
{
perror("key fail \n");
return -1;
}
msgid1= msgget ( key1,IPC_CREAT|0644 );
msgid = msgget ( key, IPC_CREAT|0644 );
if((msgid==-1)||(msgid1==-1))
{
perror(" msgget failure --->");
return -2;
}
printf("key:%xkey1:%x msgid:%d msgid1:%d 消息队列创建获取成功\n", key,key1,msgid,msgid1);
/*客户端发送数据*/
snd_msg.mtype=snd_msg.cpid=getpid();
sprintf(snd_msg.msg, "--->进程%d发送给服务器的消息<---",snd_msg.cpid);
ret = msgsnd( msgid,(void *)&snd_msg, sizeof(snd_msg)-sizeof(long), 0);
if( ret<0 )
{
perror("msgsnd failure--->");
return -3;
}
/*客户端接收数据*/
int n=msgrcv(msgid1,(void *)&send_p,sizeof(send_p)-sizeof(long),(long)pid,0);
if(n<0){
perror("客户端接收数据失败\n");
return -4;
}
printf("客户端从服务端获取的数据是【%s】:\n",send_p.input);
return 0;
}
- 服务端代码
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
struct send{
long mtype;
char input[256];
};
struct msgbuf {
long mtype;
int id;
char Mess[500];
};
int main( void )
{
key_t key,key1;
int msgid,ret,msgid2;
struct msgbuf msg;
struct send send_p;
key = ftok( "/tmp", 0 );
key1=ftok("/tmp",9);
if(key1<0){
perror("fail\n");
}
if(key<0){
perror("fail\n");
}
msgid = msgget ( key, IPC_CREAT|0644 );
msgid2= msgget ( key1, IPC_CREAT|0644 );
if(msgid==-1)
{
perror(" msgget fail --->");
return -2;
}
printf("key:%xkey1:%x msgid:%d msgid1:%d 消息队列创建获取成功\n", key,key1,msgid,msgid2);
/*服务端从客户端接受数据*/
while(1){
ret = msgrcv( msgid,(void *)&msg, sizeof(msg)-sizeof(long), 0, 0);
if( ret<0 )
{
perror(" read msg failure......");
return -3;
}
printf("服务端从[%d]获取的数据是:【%s】\n",msg.id,msg.Mess);
/*服务端向客户端发送数据*/
send_p.mtype=msg.id;
sprintf(send_p.input,"你好[%d]客户端进程",msg.id);
int Send=msgsnd(msgid2,(void *)&send_p,sizeof(send_p)-sizeof(long),0);
if(Send<0){
perror("信息发送失败\n");
return -1;
}
}
return 0;
}
只要在msgrcv函数中第三个函数中使用进程id 就可以实现此功能