Я пытаюсь узнать и понять, что такое очередь сообщений. Я получил код здесь (я скопировал их из Интернета и немного изменил их в соответствии с моим примером). Это send.c, которые позволят вам ввести некоторые простые операции в тексте и отправить их в очередь сообщений. Файл receive.c получит эти операции, вычислит его и распечатает результат на экране.Обратный звонок очереди сообщений
Что я хочу сделать дальше (но я не знаю, как это сделать), чтобы сделать операцию вычисления receive.c, а затем отправит каждый результат каждому сообщению от send.c. Поэтому, пожалуйста, помогите мне, я вроде застрял :(
send.c:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct my_msgbuf {
long mtype;
char mtext[200];
};
int main() {
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("send.c", 'B')) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0777 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
printf("Enter lines of message, ^D to quit:\n");
buf.mtype = 1;
while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) {
int len = strlen(buf.mtext);
if (buf.mtext[len-1] == '\n') {
buf.mtext[len-1] = '\0';
}
if (msgsnd(msqid, &buf, len+1, 0) == -1) {
perror("msgsnd");
}
}
if (msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
receive.c:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
struct my_msgbuf {
long mtype;
char mtext[200];
};
int calculate(char mtext[200]) {
int result = 0;
char number_1[20];
char number_2[20];
char operator;
int pos = 0;
for (int i = 0; i < strlen(mtext); i++) {
if (mtext[i] == '+' || mtext[i] == '-' || mtext[i] == '*' || mtext[i] == '/') {
operator = mtext[i];
pos = i + 2;
break;
}
number_1[i] = mtext[i];
}
number_1[pos-3] = '\0';
for (int j = pos; j <= strlen(mtext); j++) {
number_2[j - pos] = mtext[j];
}
switch(operator) {
case '+':
result = atoi(number_1) + atoi(number_2);
break;
case '-':
result = atoi(number_1) - atoi(number_2);
break;
case '*':
result = atoi(number_1) * atoi(number_2);
break;
case '/':
result = atoi(number_1)/atoi(number_2);
break;
}
return result;
}
int main() {
struct my_msgbuf buf;
int msqid;
key_t key;
if ((key = ftok("send.c", 'B')) == -1) {
perror("ftok");
exit(1);
}
if ((msqid = msgget(key, 0777 | IPC_CREAT)) == -1) {
perror("msgget");
exit(1);
}
printf("Ready to receive messages...\n");
for(;;) {
if (msgrcv(msqid, &buf, sizeof buf.mtext, 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
int result = calculate(buf.mtext);
printf("%s = %d\n", buf.mtext, result);
}
return 0;
}
При запуске те файлы, они будут выглядеть следующим образом: