From c5735552a2b0f14708b934577b190209c9a6e5b5 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Sun, 22 Sep 2019 15:05:12 -0400 Subject: [PATCH] Add basic RecvMsg routine --- mailbox.c | 25 +++++++++++++++++++++++++ mailbox.h | 1 + 2 files changed, 26 insertions(+) diff --git a/mailbox.c b/mailbox.c index ed8b544..39b7de2 100644 --- a/mailbox.c +++ b/mailbox.c @@ -77,5 +77,30 @@ int SendMsg(int dest, struct msg *message) { // Signal that someone can recieve a message, now that it's stored. sem_post(&dest_mailbox->recv_sem); + return 0; +} + +/** + * Receive a message from the given mailbox. + * + * @param mailbox_index The index of the mailbox to receive from. + * @param message A pointer to an already allocated message struct to store the recieved message in. + * @return int -1 on error, 0 otherwise. + */ +int RecvMsg(int mailbox_index, struct msg *message) { + if (mailbox_index >= num_mailboxes || mailbox_index < 0) { + return -1; + } + + struct mailbox *src_mailbox = &mailboxes[mailbox_index]; + int wait_result = sem_wait(&src_mailbox->recv_sem); + if (wait_result != 0) { + return -1; + } + + memcpy(message, &src_mailbox->stored_message, sizeof(struct msg)); + // Signal that someone can send a message to this mailbox now that we've taken the message out. + sem_post(&src_mailbox->send_sem); + return 0; } \ No newline at end of file diff --git a/mailbox.h b/mailbox.h index b30a543..44caa4b 100644 --- a/mailbox.h +++ b/mailbox.h @@ -30,5 +30,6 @@ int init_mailboxes(int n); void free_mailboxes(); // God I hate the caps, but this is the required definition. int SendMsg(int dest, struct msg *message); +int RecvMsg(int mailbox_index, struct msg *message); #endif \ No newline at end of file