使用消息队列实现两个进程间的相互通信
代码:
1.c
#include <head.h>
struct msgbuf
{
long mtype;
char mtext[1024];
char ntext[1024];
};
#define SIZE sizeof(struct msgbuf)-sizeof(long)
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if( pid < 0)
{
perror("fork");
return -1;
}
key_t key = ftok("./",'k');
if(key == -1)
{
perror("ftok");
return -1;
}
int msgid = msgget(key, IPC_CREAT |0664);
if(msgid == -1)
{
perror("msgget");
return -1;
}
struct msgbuf info = {.mtype = 100};
if(pid > 0)
{
struct msgbuf info = {.mtype = 50};
while(1)
{
bzero(info.ntext,sizeof(info.ntext));
msgrcv(msgid,&info,SIZE,50,0);
printf("消息为%s\n",info.ntext);
if(strcmp(info.ntext,"\0") == 0)
{
break;
}
}
}
else if(pid == 0)
{
while(1)
{
bzero(info.mtext,sizeof(info.mtext));
// printf("请输入:");
fgets(info.mtext,SIZE,stdin);
info.mtext[strlen(info.mtext)-1] = 0;
msgsnd(msgid,&info,SIZE,0);
if(strcmp(info.mtext,"quit") == 0)
{
break;
}
}
if(msgctl(msgid,IPC_RMID,NULL) == -1)
{
perror("msgctl");
return -1;
}
exit(0);
}
wait(NULL);
return 0;
}
2.c
#include <head.h>
struct msgbuf
{
long mtype;
char mtext[1024];
char ntext[1024];
};
#define SIZE sizeof(struct msgbuf)-sizeof(long)
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if( pid < 0 )
{
perror("fork");
return -1;
}
key_t key = ftok("./",'k');
if(key == -1)
{
perror("ftok");
return -1;
}
int msgid = msgget(key, IPC_CREAT |0664);
if(msgid == -1)
{
perror("msgget");
return -1;
}
if(pid > 0)
{
struct msgbuf info = {.mtype = 100};
while(1)
{
bzero(info.mtext,sizeof(info.mtext));
msgrcv(msgid,&info,SIZE,100,0);
printf("消息为%s\n",info.mtext);
if(strcmp(info.mtext,"\0") == 0)
{
break;
}
}
}
else if(pid == 0)
{
struct msgbuf info = {.mtype = 50};
while(1)
{
bzero(info.ntext,sizeof(info.ntext));
// printf("请输入:");
fgets(info.ntext,SIZE,stdin);
info.ntext[strlen(info.ntext)-1] = 0;
msgsnd(msgid,&info,SIZE,0);
if(strcmp(info.ntext,"quit") == 0)
{
break;
}
}
if(msgctl(msgid,IPC_RMID,NULL) == -1)
{
perror("msgctl");
return -1;
}
exit(0);
}
wait(NULL);
return 0;
}
运行结果:
思维导图: