#include <myhead.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
void *task1(void *arg)
{
int msqid = *(int *)arg;
struct msgbuf msbuf;
printf("陈:\n\t");
fflush(stdout);
while(1)
{
msbuf.mtype = 1;
fgets(msbuf.mtext,sizeof(msbuf.mtext),stdin);
msbuf.mtext[strlen(msbuf.mtext)-1]='\0';
if(msgsnd(msqid,&msbuf,sizeof(msbuf)-sizeof(long),0)==-1)
{
perror("msgsnd");
return NULL;
}
printf("陈:\n\t");
fflush(stdout);
if(!strcmp(msbuf.mtext,"quit"))
{
system("clear");
exit(0);
}
}
pthread_exit(NULL);
}
void *task2(void *arg)
{
int msqid = *(int *)arg;
struct msgbuf buf;
ssize_t num = 0;
while(1)
{
bzero(&buf,sizeof(buf));
if((num = msgrcv(msqid,&buf,sizeof(buf.mtext),2,0))<0)
{
//perror("msgsnd");
return NULL;
}
printf("\n李:\n\t%s\n",buf.mtext);
printf("陈:\n\t");
fflush(stdout);
if(!strcmp(buf.mtext,"quit"))
{
msgctl(msqid,IPC_RMID,NULL);
system("clear");
exit(0);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
key_t key = ftok("./",0);
if(key == -1)
{
perror("fork error");
return -1;
}
umask(0);
int msqid = msgget(key,IPC_CREAT|0664);
if(msqid == -1)
{
perror("msgget error");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,task1,&msqid)!=0)
{
printf("线程1创建失败\n");
}
if(pthread_create(&tid2,NULL,task2,&msqid)!=0)
{
printf("线程2创建失败\n");
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
#include <myhead.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
void *task1(void *arg)
{
int msqid = *(int *)arg;
struct msgbuf msbuf;
printf("李:\n\t");
fflush(stdout);
while(1)
{
msbuf.mtype = 2;
fgets(msbuf.mtext,sizeof(msbuf.mtext),stdin);
msbuf.mtext[strlen(msbuf.mtext)-1]='\0';
if(msgsnd(msqid,&msbuf,sizeof(msbuf)-sizeof(long),0)==-1)
{
perror("msgsnd");
return NULL;
}
printf("李:\n\t");
fflush(stdout);
if(!strcmp(msbuf.mtext,"quit"))
{
system("clear");
exit(0);
}
}
pthread_exit(NULL);
}
void *task2(void *arg)
{
int msqid = *(int *)arg;
struct msgbuf buf;
ssize_t num = 0;
while(1)
{
bzero(&buf,sizeof(buf));
if((num = msgrcv(msqid,&buf,sizeof(buf.mtext),1,0))<0)
{
//perror("msgsnd");
return NULL;
}
printf("\n陈:\n\t%s\n",buf.mtext);
printf("李:\n\t");
fflush(stdout);
if(!strcmp(buf.mtext,"quit"))
{
msgctl(msqid,IPC_RMID,NULL);
system("clear");
exit(0);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
key_t key = ftok("./",0);
if(key == -1)
{
perror("fork error");
return -1;
}
umask(0);
int msqid = msgget(key,IPC_CREAT|0664);
if(msqid == -1)
{
perror("msgget error");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,task1,&msqid)!=0)
{
printf("线程1创建失败\n");
}
if(pthread_create(&tid2,NULL,task2,&msqid)!=0)
{
printf("线程2创建失败\n");
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}