Процесс получения не получает сообщение из очереди сообщений - PullRequest
0 голосов
/ 03 марта 2020

Я пытаюсь смоделировать межпроцессное взаимодействие, используя

очереди сообщений. Моя программа должна запускать три программы: master. cpp, отправитель. cpp и получатель. cpp, что должно быть скомпилированными в исполняемые файлы с именами master, sender и receive соответственно

Master создает очередь сообщений и создает два дочерних процесса: получатель и отправитель. Отправитель должен отправить сообщение, а получатель - получить сообщение.

Я действительно в растерянности, почему это не работает. Я запускаю программы, используя отдельные терминалы, и сообщение не принимается. Я не вижу, где моя ошибка. Любое объяснение, почему оно не работает, приветствуется.

Мастер. cpp

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>

using namespace std;

int main()
{
//  Creates a message queue
int queueID = msgget(IPC_PRIVATE, IPC_EXCL|IPC_CREAT|0600);


//  Converting the interger value into a string
string queueIDString = to_string(queueID);

//Converting the string to a char so it can be passed as an argument to various system calls
char const *msgQueueID = queueIDString.c_str();

cout << "Master, PID : " << msgQueueID << " begins execution" << endl;

//  Creatinges the Receiver process
pid_t cPID = fork();
if(cPID < 0) {
    cout << "Failed to create child process." << endl;
    return 1;
}
else if(cPID == 0) {
    // Receiving process exutes, passing the message queue ID as an argument
    execlp("./receiver", msgQueueID, NULL);
    cout << "PID of receiver process: " << getpid() << endl;
    exit(0);
}

//  Creating the Sender process
cPID = fork();
if(cPID < 0) {
    cout << "Failed to create child process." << endl;
    return 1;
}
else if(cPID == 0) {
    //  Sending message program execution, passing the message queue ID as an argument
    execlp("./sender", msgQueueID, NULL);
    cout << "PID of sender process: " << getpid() << endl;

    exit(0);
}

//  Waits for child processes to finish executing
while(wait(NULL) != -1);

//Removing the message queue
msgctl(queueID, IPC_RMID, NULL);

cout << "Message Queue " << queueID << " has been removed" << endl;

exit(0);    //parent process will now terminate

return 0;
}

Отправитель. cpp

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string>

using namespace std;

// declaring global message buffer
struct buf {
long mtype;
char greeting[50];  // message content
};

//Function that gets user input and sends it to the message queue
void sendMessage(int queueID) {
buf msg;                                //  message buffer
int size = sizeof(msg) - sizeof(long);  //  size of the message buffer - size of a long variable
msg.mtype = 114;                        //  prepare message with myupr = 114
string message;                         //  stores user input


//Pauses the sender process for 2 seconds
sleep(2);
cout << "Enter a message: ";

//Stores user input into the message buffer character array greeting
getline(cin, message);
strcpy(msg.greeting, message.c_str());

//Outputs the message sent along with the sender process ID
cout << "Sender, " << "PID " << getpid() << " sends message to Message Queue " << queueID << endl;
cout << "Message Sent: " << msg.greeting << endl;

//  Sends the message to the message queue
msgsnd(queueID, (struct msgbuf *)&msg, size, 0);
}

int main(int argc, const char* argv[]) {
cout << "Sender, " << "PID " << getpid() << ", begins execution" << endl;
int msgq_id = atoi(argv[0]);    //  Gets the queue ID from the argument executed from master.cpp
sendMessage(msgq_id);
return 0;
}

Получатель. cpp

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
using namespace std;

// declaring global message buffer
struct buf {
long mtype; // required
char greeting[50];  // message content
};

//Receives a message from the message queue and prints it out
void recieveMessage(int queueID) {
buf msg;
int size = sizeof(msg) - sizeof(long);  //  size of the message buffer - size of a long variable

//Receives the message with mtype=114 from the message queue associated with qid
msgrcv(queueID, (struct msgbuf *)&msg, size, 114, 0);

//Outputs the message received
cout << "Receiver, " << "PID " << getpid() << " receives message from Message Queue " << queueID << endl;
cout << "Message Received: " << msg.greeting << endl;
}

int main(int argc, const char* argv[]) {
cout << "Receiver, " << "PID " << getpid() << ", begins execution" << endl;
int msgq_id = atoi(argv[0]);    //  Gets the queue ID from the argument executed from master.cpp
recieveMessage(msgq_id);
return 0;
}
...