不爱学习的那谁 的学生作业:
#include
#include
#include
#include
#include
#include
#include
#include
#define PATHNAME "."
#define PRO_ID 10
#define MSG_TYPE_A 100
#define MSG_TYPE_B 200
#define MSG_SZ 64
// 发送的 消息结构体
struct msgbuf{
long mtype;
char mtext[MSG_SZ];
};
int main(void)
{
pid_t cpid;
key_t key;
int msgid, retA, retB;
char buffer[MSG_SZ];
ssize_t rbytes;
struct msgbuf msgA;
struct msgbuf msgB;
struct msgbuf rcv_msg;
key = ftok(PATHNAME, PRO_ID);
if(key == -1){
perror("fotk(): ");
exit(EXIT_FAILURE);
}
msgid = msgget(key, IPC_CREAT | 0666);
if(msgid == -1)
{
perror("msgget(): ");
exit(EXIT_FAILURE);
}
printf("msg id : %d\n",msgid);
cpid = fork();
if (cpid == -1) {
perror("[ERROR] fork(): ");
exit(EXIT_FAILURE);
} else if (cpid == 0) { // 子进程A
while(1) {
// 接收消息
rbytes = msgrcv(msgid, (void *)&rcv_msg, MSG_SZ, MSG_TYPE_A, 0);
if(rbytes == -1){
perror("[ERROR] msgrcv(): ");
exit(EXIT_FAILURE);
}
printf("进程A: mtype : %ld\n", rcv_msg.mtype);
printf("进程A: mtext : %s\n", rcv_msg.mtext);
}
} else if (cpid > 0) { // 父进程
cpid = fork();
if (cpid == -1) {
perror("[ERROR] fork(): ");
exit(EXIT_FAILURE);
} else if (cpid == 0) { // 子进程B
while(1) {
// 接收消息
rbytes = msgrcv(msgid, (void *)&rcv_msg, MSG_SZ, MSG_TYPE_B, 0);
if (rbytes == -1) {
perror("[ERROR] msgrcv(): ");
exit(EXIT_FAILURE);
}
printf("进程B: mtype : %ld\n", rcv_msg.mtype);
printf("进程B: mtext : %s\n", rcv_msg.mtext);
}
} else if (cpid > 0) { // 父进程
while (1) {
fgets(buffer, sizeof(buffer), stdin);
if (strcmp(buffer, "quit") == 0) {
printf("GoodBye!\n");
exit(EXIT_SUCCESS);
}
msgA.mtype = MSG_TYPE_A; // 子进程A
strcpy(msgA.mtext, buffer);
msgB.mtype = MSG_TYPE_B; // 子进程B
strcpy(msgB.mtext, buffer);
// 发送消息
retA = msgsnd(msgid, (const void *)&msgA, strlen(msgA.mtext) + 1, 0);
retB = msgsnd(msgid, (const void *)&msgB, strlen(msgB.mtext) + 1, 0);
if (retA == -1 || retB == -1) {
perror("msgsnd(): ");
exit(EXIT_FAILURE);
}
}
}
}
return 0;
}
【图片】
【图片】