慕先生4541263 的学生作业:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define PATHNAME "."
#define PROID 10
#define MAX_MSG_SIZE 100
#define MTYPE_A 100
#define MTYPE_B 200
typedef struct msgbuf {
long mtype;
char mtext[MAX_MSG_SIZE];
} Message;
void process_a(int msgid) {
Message message;
while (1) {
if (msgrcv(msgid, &message, MAX_MSG_SIZE, MTYPE_A, 0) == -1) {
perror("[ERROR] msgrcv():");
exit(EXIT_FAILURE);
}
if (strcmp(message.mtext, "quit") == 0) {
break;
}
printf("pid(%d) receive the message: %s\n", getpid(), message.mtext);
}
printf("pid(%d) exit\n", getpid());
}
void process_b(int msgid) {
Message message;
while (1) {
if (msgrcv(msgid, &message, MAX_MSG_SIZE, MTYPE_B, 0) == -1) {
perror("[ERROR] msgrcv():");
exit(EXIT_FAILURE);
}
if (strcmp(message.mtext, "quit") == 0) {
break;
}
printf("pid(%d) receive the message: %s\n", getpid(), message.mtext);
}
printf("pid(%d) exit\n", getpid());
}
int main() {
key_t key;
int msgid;
pid_t pid_a, pid_b;
Message message;
key = ftok(PATHNAME, PROID);
if (key == -1)
{
perror("[ERROR] ftok():");
exit(EXIT_FAILURE);
}
msgid = msgget(key, IPC_CREAT | 0666);
if (msgid == -1) {
perror("[ERROR] msgget():");
exit(EXIT_FAILURE);
}
pid_a = fork();
if (pid_a < 0) {
perror("[ERROR] fork():");
msgctl(msgid, IPC_RMID, NULL);
exit(EXIT_FAILURE);
} else if (pid_a == 0) {
process_a(msgid);
exit(EXIT_SUCCESS);
}
pid_b = fork();
if (pid_b < 0) {
perror("[ERROR] fork():");
kill(pid_a, SIGKILL);
msgctl(msgid, IPC_RMID, NULL);
exit(EXIT_SUCCESS);
} else if (pid_b == 0) {
process_b(msgid);
exit(EXIT_SUCCESS);
}
char buffer[MAX_MSG_SIZE];
while (1) {
printf("please input messages: ");
fgets(buffer, sizeof(buffer), stdin);
buffer[strcspn(buffer, "\n")] = 0;
message.mtype = MTYPE_A;
strcpy(message.mtext, input);
if (msgsnd(msgid, &message, strlen(message.mtext) + 1, 0) == -1) {
perror("[ERROR] msgsnd():");
break;
}
message.mtype = MTYPE_B;
strcpy(message.mtext, input);
if (msgsnd(msgid, &message, strlen(message.mtext) + 1, 0) == -1) {
perror("[ERROR] msgsnd():");
break;
}
if (strcmp(buffer, "quit") == 0) {
break;
}
}
waitpid(pid_a, NULL, 0);
waitpid(pid_b, NULL, 0);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}