Introduction To Distributed Programming System V IPC: Message Queues, Shared Memory, Semaphores
Introduction To Distributed Programming System V IPC: Message Queues, Shared Memory, Semaphores
Message Queues
Shared Memory
Semaphores
System V IPC
• System V IPC was first introduced in SVR2, but
is available now in most versions of unix
• Message Queues represent linked lists of
messages, which can be written to and read from
• Shared memory allows two or more processes to
share a region of memory, so that they may each
read from and write to that memory region
• Semaphores synchronize access to shared
resources by providing synchronized access
among multiple processes trying to access those
critical resources.
Message Queues
• A Message Queue is a linked list of message
structures stored inside the kernel’s memory
space and accessible by multiple processes
• Synchronization is provided automatically by the
kernel
• New messages are added at the end of the queue
• Each message structure has a long message type
• Messages may be obtained from the queue either
in a FIFO manner (default) or by requesting a
specific type of message (based on message type)
Message Structs
• Each message structure must start with a
long message type:
struct mymsg {
long msg_type;
char mytext[512]; /* rest of message */
int somethingelse;
float dollarval;
};
Message Queue Limits
• Each message queue is limited in terms of both
the maximum number of messages it can contain
and the maximum number of bytes it may contain
• New messages cannot be added if either limit is
hit (new writes will normally block)
• On linux, these limits are defined as (in
/usr/include/linux/msg.h):
– MSGMAX 8192 /*total number of messages */
– MSBMNB 16384 /* max bytes in a queue */
Obtaining a Message Queue
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
int msgget(key_t key, int msgflg);
• key is either a number or the constant IPC_PRIVATE (parent/child)
• a msgid is returned
• key_t ftok(const char * path, int id) will return a key value for IPC
usage
• The key parameter is either a non-zero identifier for the queue to be
created or the value IPC_PRIVATE, which guarantees that a new
queue is created.
• The msgflg parameter is the read-write permissions for the queue
OR’d with one of two flags:
– IPC_CREAT will create a new queue or return an existing one
– IPC_EXCL added will force the creation of a new queue, or
return an error
Writing to a Message Queue
int msgsnd(int msqid, const void * msg_ptr,
size_t msg_size, int msgflags);