1> 使用消息队列完成两个进程间相互
a:
#include<myhead.h>
#define MSGSIZE sizeof(struct msgbuf)-sizeof(long)
struct msgbuf
{
long mtype;
char mtext[1024];
};
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(pid>0)
{
key_t key = 0;
if((key=ftok("/",'k'))==-1)
{
perror("ftok error");
return -1;
}
printf("ftok success key = %#x\n",key);
int msqid = -1;
if((msqid = msgget(key,IPC_CREAT|0664))==-1)
{
perror("msgget error");
return -1;
}
printf("msgget success msqid = %d\n",msqid);
struct msgbuf sbuf;
while(1)
{
bzero(sbuf.mtext, sizeof(sbuf.mtext));
printf("消息类型:");
scanf("%ld",&sbuf.mtype);
getchar();
printf("请输入正文:");
fgets(sbuf.mtext,sizeof(sbuf.mtext), stdin);
sbuf.mtext[strlen(sbuf.mtext)-1]=0;
msgsnd(msqid,&sbuf, MSGSIZE, 0);
printf("发送成功\n");
if(strcmp(sbuf.mtext, "quit")==0)
{
break;
}
}
}else if(pid==0)
{
key_t key1 = 0;
if((key1=ftok("/",'k'))==-1)
{
perror("ftok error");
return -1;
}
printf("ftok success key1 = %#x\n",key1);
int msqid1 = -1;
if((msqid1 = msgget(key1,IPC_CREAT|0664))==-1)
{
perror("msgget error");
return -1;
}
printf("msgget success msqid1 = %d\n",msqid1);
struct msgbuf rbuf;
while(1)
{
bzero(rbuf.mtext, sizeof(rbuf.mtext));
msgrcv(msqid1,&rbuf,MSGSIZE,2,0);
printf("收到消息为:%s\n",rbuf.mtext);
if(strcmp(rbuf.mtext, "quit")==0)
{
break;
}
}
if(msgctl(msqid1,IPC_RMID,NULL)!=0)
{
perror("msgctl error");
return -1;
}
}
else
{
perror("fork error");
return -1;
}
return 0;
}
b:
#include<myhead.h>
#define MSGSIZE sizeof(struct msgbuf)-sizeof(long)
struct msgbuf
{
long mtype;
char mtext[1024];
};
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(pid>0)
{
key_t key = 0;
if((key=ftok("/",'k'))==-1)
{
perror("ftok error");
return -1;
}
printf("ftok success key = %#x\n",key);
int msqid = -1;
if((msqid = msgget(key,IPC_CREAT|0664))==-1)
{
perror("msgget error");
return -1;
}
printf("msgget success msqid = %d\n",msqid);
struct msgbuf sbuf;
while(1)
{
bzero(sbuf.mtext, sizeof(sbuf.mtext));
printf("消息类型:");
scanf("%ld",&sbuf.mtype);
getchar();
printf("请输入正文:");
fgets(sbuf.mtext,sizeof(sbuf.mtext), stdin);
sbuf.mtext[strlen(sbuf.mtext)-1]=0;
msgsnd(msqid,&sbuf, MSGSIZE, 0);
printf("发送成功\n");
if(strcmp(sbuf.mtext, "quit")==0)
{
break;
}
}
}else if(pid==0)
{
key_t key1 = 0;
if((key1=ftok("/",'k'))==-1)
{
perror("ftok error");
return -1;
}
printf("ftok success key1 = %#x\n",key1);
int msqid1 = -1;
if((msqid1 = msgget(key1,IPC_CREAT|0664))==-1)
{
perror("msgget error");
return -1;
}
printf("msgget success msqid = %d\n",msqid1);
struct msgbuf rbuf;
while(1)
{
bzero(rbuf.mtext, sizeof(rbuf.mtext));
msgrcv(msqid1,&rbuf,MSGSIZE,1,0);
printf("收到消息为:%s\n",rbuf.mtext);
if(strcmp(rbuf.mtext, "quit")==0)
{
break;
}
}
if(msgctl(msqid1,IPC_RMID,NULL)!=0)
{
perror("msgctl error");
return -1;
}
}
else
{
perror("fork error");
return -1;
}
return 0;
}