通过消息队列实现两进程间通信

环境:linux C

功能:通过消息队列实现两进程间通信

/*clientA*/

#include <stdio.h>

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <pthread.h>
//定义消息类型
typedef struct 
{
long mtype;
char mtext[32];
}MSG;
#define LEN (sizeof(MSG) - sizeof(long))
#define typeA 100
#define typeB 200
void * rcv_function(void * arg);


key_t key;//与ipc相关联的KEY
int msgid;
MSG bufsnd,bufrcv;
int main()
{
pthread_t rcv_thread;
//创建key
if((key = ftok(".",'q')) == -1)
{
perror("ftok");
exit(-1);
}
//创建消息队列
if((msgid = msgget(key,IPC_CREAT|0666)) < 0)
{
perror("msgget");
exit(-1);
}
//rcv_thread
if(pthread_create(&rcv_thread,NULL,rcv_function,NULL) != 0)
{
printf("fail to create pthread\n");
exit(-1);
}

while(1)
{
bufsnd.mtype = typeB;
printf("input >\n");
fgets(bufsnd.mtext,32,stdin);
msgsnd(msgid,&bufsnd,LEN,0);
if(strcmp(bufsnd.mtext, "quit\n") == 0 )
break;
}
return 0;
}


void * rcv_function(void * arg)
{
while(1)
{
if(msgrcv(msgid,&bufrcv,LEN,typeA,0) < 0 )
{
perror("msgrcv");
exit(-1);
}
if(strcmp(bufrcv.mtext,"quit\n") == 0)
{
msgctl(msgid,IPC_RMID,NULL);
break;
}
printf("clientB:%s",bufrcv.mtext);
printf("--------------------------------------------\n");
}


}

/*clientB*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <pthread.h>
//定义消息类型
typedef struct 
{
long mtype;
char mtext[32];
}MSG;
#define LEN (sizeof(MSG) - sizeof(long))
#define typeA 100
#define typeB 200
void * rcv_function(void * arg);


key_t key;//与ipc相关联的KEY
int msgid;
MSG bufsnd,bufrcv;
int main()
{
pthread_t rcv_thread;
//创建key
if((key = ftok(".",'q')) == -1)
{
perror("ftok");
exit(-1);
}
//创建消息队列
if((msgid = msgget(key,IPC_CREAT|0666)) < 0)
{
perror("msgget");
exit(-1);
}
//rcv_thread
if(pthread_create(&rcv_thread,NULL,rcv_function,NULL) != 0)
{
printf("fail to create pthread\n");
exit(-1);
}

while(1)
{
bufsnd.mtype = typeA;
printf("input >\n");
fgets(bufsnd.mtext,32,stdin);
msgsnd(msgid,&bufsnd,LEN,0);
if(strcmp(bufsnd.mtext, "quit\n") == 0 )
break;
}
return 0;
}


void * rcv_function(void * arg)
{
while(1)
{
if(msgrcv(msgid,&bufrcv,LEN,typeB,0) < 0 )
{
perror("msgrcv");
exit(-1);
}
if(strcmp(bufrcv.mtext,"quit\n") == 0)
{
msgctl(msgid,IPC_RMID,NULL);
break;
}
printf("clientA:%s",bufrcv.mtext);
printf("----------------------------------------------\n");
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值