使用消息进程完成两个进程之间的互相通信
222端
#include <myhead.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
#define SIZE (sizeof(struct msgbuf)-sizeof(long))
int main(int argc, const char *argv[])
{
//key
key_t key=ftok("/",'k');
if(key==-1)
{
perror("key create error");
return -1;
}
printf("key=%#x\n",key);
//queue
int msgid=msgget(key,IPC_CREAT|0664);
if(msgid==-1)
{
perror("msgget error");
return -1;
}
printf("msgid=%d\n",msgid);
//queue data
struct msgbuf buf;
struct msgbuf buf1;
pid_t pid;
pid=fork();
if(pid>0)
{
while(1)
{
printf("plz enter datatype: ");
scanf("%ld",&buf.mtype);
printf("plz enter words: ");
scanf("%s",buf.mtext);
msgsnd(msgid,&buf,SIZE,0);
if(strcmp(buf.mtext,"quit")==0)
{
break;
}
}
}
else if(pid==0)
{
while(1)
{
msgrcv(msgid,&buf1,SIZE,222,0);
printf("收到消息: %s\n",buf1.mtext);
if(strcmp(buf1.mtext,"quit")==0)
{
break;
}
}
}
else
{
perror("fork error");
}
//delete
return 0;
}
121端
#include <myhead.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
#define SIZE (sizeof(struct msgbuf)-sizeof(long))
int main(int argc, const char *argv[])
{
//key
key_t key=ftok("/",'k');
if(key==-1)
{
perror("key create error");
return -1;
}
printf("key=%#x\n",key);
//queue
int msgid=msgget(key,IPC_CREAT|0664);
if(msgid==-1)
{
perror("msgget error");
return -1;
}
printf("msgid=%d\n",msgid);
//queue data
struct msgbuf buf;
struct msgbuf buf1;
pid_t pid;
pid=fork();
if(pid>0)
{
while(1)
{
printf("plz enter datatype: ");
scanf("%ld",&buf.mtype);
printf("plz enter words: ");
scanf("%s",buf.mtext);
msgsnd(msgid,&buf,SIZE,0);
if(strcmp(buf.mtext,"quit")==0)
{
break;
}
}
}
else if(pid==0)
{
while(1)
{
msgrcv(msgid,&buf1,SIZE,222,0);
printf("收到消息: %s\n",buf1.mtext);
if(strcmp(buf1.mtext,"quit")==0)
{
break;
}
}
}
else
{
perror("fork error");
}
//delete
return 0;
}
ubuntu@ubuntu:hw2$ cat rec.c
#include <myhead.h>
struct msgbuf
{
long mtype;
char mtext[1024];
};
#define SIZE (sizeof(struct msgbuf)-sizeof(long))
int main(int argc, const char *argv[])
{
//key
key_t key=ftok("/",'k');
if(key==-1)
{
perror("key create error");
return -1;
}
printf("key=%#x\n",key);
//queue
int msgid=msgget(key,IPC_CREAT|0664);
if(msgid==-1)
{
perror("msgget error");
return -1;
}
printf("msgid=%d\n",msgid);
//queue data
struct msgbuf buf;
struct msgbuf buf1;
pid_t pid1;
pid1=fork();
if(pid1>0)
{
while(1)
{
msgrcv(msgid,&buf,SIZE,121,0);
printf("收到消息: %s\n",buf.mtext);
if(strcmp(buf.mtext,"quit")==0)
{
break;
}
}
}
else if(pid1==0)
{
while(1)
{
printf("plz enter datatype: ");
scanf("%ld",&buf1.mtype);
printf("plz enter words: ");
scanf("%s",buf1.mtext);
msgsnd(msgid,&buf1,SIZE,0);
if(strcmp(buf1.mtext,"quit")==0)
{
break;
}
}
}
else
{
perror("fork error");
}
//delete
return 0;
}