qq_康斯坦丁_0 的學生作業:
#include
#include
#include
#include
#include
#include
#include
#include
#define MSG_KEY 1234
#define MAX_MSG_SIZE 256
// 消息結構
struct msg_buffer {
long msg_type;
char msg_text[MAX_MSG_SIZE];
};
void child_process(int msgid, int type) {
struct msg_buffer message;
while (1) {
if (msgrcv(msgid, &message, sizeof(message.msg_text), type, 0) < 0) {
perror(“msgrcv”);
exit(1);
}
printf(“子進程 (類型 %d) 收到消息: %s”, type, message.msg_text);
if (strncmp(message.msg_text, “quit”, 4) == 0) {
break;
}
}
exit(0);
}
int main() {
int msgid;
pid_t pid_a, pid_b;
struct msg_buffer message;
char input_buffer[MAX_MSG_SIZE];
// 創建消息隊列
msgid = msgget(MSG_KEY, 0666 | IPC_CREAT);
if (msgid < 0) {
perror("msgget");
exit(1);
}
// 創建子進程A
pid_a = fork();
if (pid_a < 0) {
perror("fork A");
exit(1);
}
if (pid_a == 0) {
child_process(msgid, 100);
}
// 創建子進程B
pid_b = fork();
if (pid_b < 0) {
perror("fork B");
exit(1);
}
if (pid_b == 0) {
child_process(msgid, 200);
}
// 父進程
printf("父進程啟動,請輸入要發送的消息 ('quit' 退出):\n");
while (1) {
printf("> ");
fgets(input_buffer, sizeof(input_buffer), stdin);
// 發送給子進程A
message.msg_type = 100;
strcpy(message.msg_text, input_buffer);
if (msgsnd(msgid, &message, sizeof(message.msg_text), 0) < 0) {
perror("msgsnd to A");
exit(1);
}
// 發送給子進程B
message.msg_type = 200;
strcpy(message.msg_text, input_buffer);
if (msgsnd(msgid, &message, sizeof(message.msg_text), 0) < 0) {
perror("msgsnd to B");
exit(1);
}
if (strncmp(input_buffer, "quit", 4) == 0) {
break;
}
}
// 等待子進程結束
waitpid(pid_a, NULL, 0);
waitpid(pid_b, NULL, 0);
// 刪除消息隊列
if (msgctl(msgid, IPC_RMID, NULL) < 0) {
perror("msgctl");
exit(1);
}
printf("父進程退出\n");
return 0;
}