使用消息队列实现两个进程间的相互通信
#include<head.h>
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[64]; /* message data */
};
void* fun1(void* arg)
{
int msqid=*(int*)arg;
struct msgbuf info;
while(1)
{
if(msgrcv(msqid,&info,sizeof(info.mtext),1,0)<0)
{
ERR_MSG("msgrcv");
return NULL;
}
if(strcmp(info.mtext,"quit")==0)
exit(0);
puts(info.mtext);
}
}
void* fun2(void* arg)
{
int msqid=*(int*)arg;
struct msgbuf info;
info.mtype=2;
while(1)
{
fgets(info.mtext,sizeof(info.mtext),stdin);
info.mtext[strlen(info.mtext)-1]=0;
if(msgsnd(msqid,&info,sizeof(info)-sizeof(info.mtype),IPC_NOWAIT)<0)
{
ERR_MSG("msgsnd");
return NULL;
}
if(strcmp(info.mtext,"quit")==0)
exit(0);
}
}
int main(int argc, const char *argv[])
{
key_t key=ftok("./",'t');
if(key<0)
{
ERR_MSG("ftok");
return -1;
}
int msqid=msgget(key,IPC_CREAT|0664);
if(msqid<0)
{
ERR_MSG("msgget");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,fun1,&msqid)<0)
{
printf("pthread_create fail\n");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,&msqid)<0)
{
printf("pthread_create fail\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
if(msgctl(msqid,IPC_RMID,NULL)<0)
{
ERR_MSG("msgctl");
return -1;
}
return 0;
}
#include<head.h>
struct msgbuf {
long mtype; /* message type, must be > 0 */
char mtext[64]; /* message data */
};
void* fun1(void* arg)
{
int msqid=*(int*)arg;
struct msgbuf info;
while(1)
{
if(msgrcv(msqid,&info,sizeof(info.mtext),2,0)<0)
{
ERR_MSG("msgrcv");
return NULL;
}
if(strcmp(info.mtext,"quit")==0)
exit(0);
puts(info.mtext);
}
}
void* fun2(void* arg)
{
int msqid=*(int*)arg;
struct msgbuf info;
info.mtype=1;
while(1)
{
fgets(info.mtext,sizeof(info.mtext),stdin);
info.mtext[strlen(info.mtext)-1]=0;
if(msgsnd(msqid,&info,sizeof(info)-sizeof(info.mtype),IPC_NOWAIT)<0)
{
ERR_MSG("msgsnd");
return NULL;
}
if(strcmp(info.mtext,"quit")==0)
exit(0);
}
}
int main(int argc, const char *argv[])
{
key_t key=ftok("./",'t');
if(key<0)
{
ERR_MSG("ftok");
return -1;
}
int msqid=msgget(key,IPC_CREAT|0664);
if(msqid<0)
{
ERR_MSG("msgget");
return -1;
}
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,fun1,&msqid)<0)
{
printf("pthread_create fail\n");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,&msqid)<0)
{
printf("pthread_create fail\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
if(msgctl(msqid,IPC_RMID,NULL)<0)
{
ERR_MSG("msgctl");
return -1;
}
return 0;
}