用线程和消息队列实现连个进程间的通讯

来源:互联网 发布:现场网络直播 编辑:程序博客网 时间:2024/06/04 19:06

gcc 编译的时候要加上-pthread

进程1:

#include <stdio.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <strings.h>
#include <unistd.h>
struct msgbuf 
{
long msgtype;       /* message type, must be > 0 */
char mtext[100];    /* message data */
};




void *route(void *arg)
{


key_t key1;
key1 = ftok(".",2);


int msgid1;


msgid1 = msgget(key1, IPC_CREAT|0666 );




struct msgbuf buf1;


while(1)
{
bzero(&buf1,sizeof(buf1));
msgrcv(msgid1,&buf1,100,2,0);
printf("%s\n",buf1.mtext);


}


}






int main (int argc, const char *argv[])
{


key_t key;
key = ftok(".",1);
pthread_t tid;


pthread_create(&tid,NULL,route,NULL);
int msgid;


msgid = msgget(key, IPC_CREAT|0666 );



struct msgbuf buf;


while(1)
{
bzero(&buf,sizeof(buf));
fgets(buf.mtext,100,stdin);
buf.msgtype = 1;
msgsnd(msgid,&buf,100,0);

}




return 0;


}



进程2:

#include<stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <strings.h>






struct msgbuf 
{
long msgtype;       /* message type, must be > 0 */
char mtext[100];    /* message data */
};




void *route1(void *arg)
{
key_t key1;
key1 = ftok(".",2);


int msgid1;


msgid1 = msgget(key1, IPC_CREAT|0666 );




struct msgbuf buf1;


while(1)
{
bzero(&buf1,sizeof(buf1));
fgets(buf1.mtext,100,stdin);
buf1.msgtype = 2;
msgsnd(msgid1,&buf1,100,0);


}


}




int main (int argc, const char *argv[])
{


key_t key;
key = ftok(".",1);
pthread_t tid;
int msgid;


pthread_create(&tid,NULL,route1,NULL);
msgid = msgget(key, IPC_CREAT|0666 );



struct msgbuf buf;


while(1)
{
bzero(&buf,sizeof(buf));
msgrcv(msgid,&buf,100,1,0);
printf("%s\n",buf.mtext);


}


return 0;


}


0 0
原创粉丝点击