学无止境呀呀呀 的学生作业:
#include
#include
#include
#include
#include
#include
#include
#include
#define buf_size 1024
struct msgbuf {
long mtype;
char mtext[buf_size];
};
int main(void) {
char pn[] = {"../"};
int pi = 2;
char buf[buf_size];
char *ret;
pid_t childA,childB;
//准备消息队列的key
key_t key = ftok(pn, pi);
if(key ==-1) {
perror("[ERROR] ftok()");
exit(EXIT_FAILURE);
}
//创建消息队列
int msgid = msgget(key,IPC_CREAT | 0666);
if(msgid == -1) {
perror("[ERROR] msgid():");
exit(EXIT_FAILURE);
}
//创建进程A
childA = fork();
if(childA == -1) {
perror("[ERROR] fork:");
exit(EXIT_FAILURE);
} else if (childA == 0) {
struct msgbuf rcv_msgA;
ssize_t rbytesA;
while(msgrcv(msgid,(void *)&rcv_msgA,buf_size,100,0)) {
if(rbytesA == -1) {
perror("[ERROR] msgrcv:");
exit(EXIT_FAILURE);
}
printf("mtypeA:%d\n",(int)rcv_msgA.mtype);
printf("mtextA:%s\n",rcv_msgA.mtext);
}
}
//进程B
childB = fork();
if(childB == -1) {
perror("[ERROR] fork():");
exit(EXIT_FAILURE);
} else if (childB == 0) {
//子进程B
struct msgbuf rcv_msgB;
while(msgrcv(msgid,(void *)&rcv_msgB,buf_size,200,0)) {
printf("mtypeB:%d\n",(int)rcv_msgB.mtype);
printf("mtextB:%s\n",rcv_msgB.mtext);
}
}
printf("请输入(quit 退出):\n");
while(fgets(buf,buf_size,stdin)){
if(strcmp("quit\n",buf) == 0 ) {
//清空队列
msgctl(msgid,IPC_RMID,NULL);
kill(childA,SIGKILL);
kill(childB,SIGKILL);
exit(EXIT_SUCCESS);
}
struct msgbuf snd_msg;
snd_msg.mtype = 100;
strcpy(snd_msg.mtext,buf);
msgsnd(msgid,&snd_msg,strlen(snd_msg.mtext)+1,0);
snd_msg.mtype = 200;
//发送到200
strcpy(snd_msg.mtext,buf);
msgsnd(msgid,&snd_msg,strlen(snd_msg.mtext)+1,0);
}
return 0;
}