#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
struct msgbuf aaa;
key_t key=0;
int mqsid=0;
ssize_t res=0;
void *callBack(void *arg)
{
while(1)
{
memset(&aaa,0,sizeof(read));
res= msgrcv(mqsid,&aaa,sizeof(aaa.mtext),100,0);
if(res<0)
{
perror("msgrcv");
exit(0);
}
if(strcmp(aaa.mtext,"quit")==0)
{
printf("程序结束\n");
exit(0);
}
printf("%ld %s\n",aaa.mtype,aaa.mtext);
}
}
int main(int argc, const char *argv[])
{
key =ftok("/home/ubuntu/",1);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("成功创建key\n");
mqsid =msgget(key,IPC_CREAT|0664);
if(msgget<0)
{
perror("msgget");
return -1;
}
printf("消息队列创建成功\n");
pthread_t tid;
if(pthread_create(&tid,NULL,callBack,NULL)!=0)
{
perror("pthread_create");
return -1;
}
while(1)
{
printf("请输入消息类型\n");
scanf("%ld",&aaa.mtype);
getchar();
if(0==aaa.mtype)
{
exit(0);
}
printf("请输入消息内容");
fgets(aaa.mtext,sizeof(aaa.mtext),stdin);
aaa.mtext[strlen(aaa.mtext)-1]='\0';
if(msgsnd(mqsid,&aaa,sizeof(aaa.mtext),0)<0)
{
perror("msgsnd");
exit(0);
}
printf("消息发送成功\n");
if(strcmp(aaa.mtext,"quit")==0)
{
printf("程序结束\n");
exit(0);
}
}
//system("ipcs -q");
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
struct msgbuf
{
long mtype;
char mtext[128];
};
struct msgbuf read1;
key_t key=0;
int mqsid=0;
ssize_t res=0;
void *callBack(void *arg)
{
while(1)
{
printf("请输入消息类型\n");
scanf("%ld",&read1.mtype);
getchar();
if(0==read1.mtype)
{
exit(0);
}
printf("请输入消息内容");
fgets(read1.mtext,sizeof(read1.mtext),stdin);
read1.mtext[strlen(read1.mtext)-1]='\0';
if(msgsnd(mqsid,&read1,sizeof(read1.mtext),0)<0)
{
perror("msgsnd");
exit(0);
}
printf("发送成功\n");
if(strcmp(read1.mtext,"quit")==0)
{
printf("退出程序\n");
exit(0);
}
}
}
int main(int argc, const char *argv[])
{
key =ftok("/home/ubuntu/",1);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("成功创建key\n");
mqsid =msgget(key,IPC_CREAT|0664);
if(msgget<0)
{
perror("msgget");
return -1;
}
printf("消息队列创建成功\n");
res=0;
pthread_t tid;
if(pthread_create(&tid,NULL,callBack,NULL)!=0)
{
perror("pthread_create");
return -1;
}
while(1)
{
memset(&read1,0,sizeof(read1));
res= msgrcv(mqsid,&read1,sizeof(read1.mtext),100,0|020000);
if(res<0)
{
perror("msgrcv");
exit(0);
}
if(strcmp(read1.mtext,"quit")==0)
{
printf("程序退出\n");
exit(0);
}
printf("%ld %s\n",read1.mtype,read1.mtext);
}
//system("ipcs -q");
//system("ipcs -q");
return 0;
}