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

环境: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");
}


}

猜你喜欢

转载自blog.csdn.net/qq_37051576/article/details/79403824