#include <myhead.h>
typedef struct msgbuf
{
long mtype;
char mtext[1024];
}msg_t;
#define SIZE sizeof(msg_t)-sizeof(long)
void* funcw(void* arg)
{
key_t wkey=ftok("./",'k');
if(wkey==-1)
{
perror("ftok");
return NULL;
}
int mspid;
if((mspid=msgget(wkey,IPC_CREAT|0664))==-1)
{
perror("msgget");
return NULL;
}
msg_t info={.mtype=2};
while(1)
{
bzero(info.mtext,SIZE);
fgets(info.mtext,SIZE,stdin);
info.mtext[strlen(info.mtext)-1]=0;
msgsnd(mspid,&info,SIZE,0);
if(!strcmp(info.mtext,"quit"))
{
exit(0);
}
}
return NULL;
}
void* funcr(void* arg)
{
key_t rkey;
if((rkey=ftok("./",'k'))==-1)
{
perror("ftok");
return NULL;
}
int mspid;
if((mspid=msgget(rkey,IPC_CREAT|0664))==-1)
{
perror("msgget");
return NULL;
}
msg_t info;
while(1)
{
bzero(info.mtext,SIZE);
msgrcv(mspid,&info,SIZE,1,0);
if(!strcmp(info.mtext,"quit"))
{
exit(0);
}
printf("%s\n",info.mtext);
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t wfd;
if((pthread_create(&wfd,NULL,funcw,NULL))!=0)
{
printf("pthread create failed!\n");
return -1;
}
pthread_t rfd;
if((pthread_create(&rfd,NULL,funcr,NULL))!=0)
{
printf("pthread create failed!\n");
return -1;
}
pthread_join(wfd,NULL);
pthread_join(rfd,NULL);
return 0;
}
#include <myhead.h>
typedef struct msgbuf
{
long mtype;
char mtext[1024];
}msg_t;
#define SIZE sizeof(msg_t)-sizeof(long)
void* funcw(void* arg)
{
key_t wkey=ftok("./",'k');
if(wkey==-1)
{
perror("ftok");
return NULL;
}
int mspid;
if((mspid=msgget(wkey,IPC_CREAT|0664))==-1)
{
perror("msgget");
return NULL;
}
msg_t info={.mtype=1};
while(1)
{
bzero(info.mtext,SIZE);
fgets(info.mtext,SIZE,stdin);
info.mtext[strlen(info.mtext)-1]=0;
msgsnd(mspid,&info,SIZE,0);
if(!strcmp(info.mtext,"quit"))
{
exit(0);
}
}
return NULL;
}
void* funcr(void* arg)
{
key_t rkey;
if((rkey=ftok("./",'k'))==-1)
{
perror("ftok");
return NULL;
}
int mspid;
if((mspid=msgget(rkey,IPC_CREAT|0664))==-1)
{
perror("msgget");
return NULL;
}
msg_t info;
while(1)
{
bzero(info.mtext,SIZE);
msgrcv(mspid,&info,SIZE,2,0);
if(!strcmp(info.mtext,"quit"))
{
exit(0);
}
printf("%s\n",info.mtext);
}
return NULL;
}
int main(int argc, const char *argv[])
{
pthread_t wfd;
if((pthread_create(&wfd,NULL,funcw,NULL))!=0)
{
printf("pthread create failed!\n");
return -1;
}
pthread_t rfd;
if((pthread_create(&rfd,NULL,funcr,NULL))!=0)
{
printf("pthread create failed!\n");
return -1;
}
pthread_join(wfd,NULL);
pthread_join(rfd,NULL);
return 0;
}
用消息队列实现通信。