Universidad de Costa Rica

Escuela de Ciencias de la Computación e Informática

CI-0122 Sistemas Operativos

Proyectos

CI0122 / Proyectos / Proyecto-01


/**
  *  C++ class to encapsulate Unix shared memory intrinsic structures and system calls
  *  Author: Operating systems (Francisco Arroyo)
  *  Version: 2023/Mar/15
  *
  * Ref.: https://en.wikipedia.org/wiki/Shared_memory
  *
 **/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#include "MailBox.h"

#define KEY 0xA12345

/**
  *  Class constructor
  *
  *  Must call "msgget" to create a mailbox
  *
  *  MailBoxkey is your student id number: 0xA12345 (to represent as hexadecimal value)
  *  size = 1
  *  MailBoxflg: IPC_CREAT | 0600
  *
 **/
MailBox::MailBox() {
   int st;

   st = msgget( KEY, IPC_CREAT | 0600 );
   if ( -1 == st ) {
      perror( "MailBox::MailBox" );
      exit( 1 );
   }

   this->id = st;

}


/**
  *   Class destructor
  *
  *   Must call msgctl
  *
 **/
MailBox::~MailBox() {
   int st = -1;

   // call msgctl to destroy this message queue
   // check for errors

   return st;
}

struct msgbuf {
   long type;	// this field must exist at first place
   char data[ MAXDATA ];	// char array for simplicity
   // user can define other fields
};


/**
  *   Send method
  *
  *   Need to call msgsnd to receive a pointer to shared memory area
  *
  *   other fields must come as parameters, or build a specialized struct
  *
 **/
int MailBox::send( long type, void * buffer, int numBytes ) {
   int st = -1;

   // must declare a msgbuf variable and set all the fields
   struct msgbuf m;
   m.type = type;
   memcpy( (void * ) m.data, buffer, numBytes );
   // set other fields if necessary

   // use msgsnd system call to send message to a queue

   return st;

}


/**
  *   receive method
  *
  *   Need to call msgrecv to receive messages from queue
  *
  *   Remember rules to receive message, see documentation
  *
 **/
int MailBox::receive( long type, void * buffer, int capacity ) {
   int st = -1;

   // must declare a msgbuf variable 
   struct msgbuf m;

   // use msgrcv system call to receive a message from the queue

   // copy data from m to parameter variables

   return st;

}