Advanced UNIX IPC Facilities

advertisement
Advanced UNIX IPC Facilities
After Haviland, et al.’s book
Introduction and Basic Concepts
• UNIX offers a variety of advanced IPC
mechanisms
• This makes UNIX an extremely rich system
in the IPC area
• Allows developer to use a variety of
approaches when programming a system
made up of cooperating tasks
Categories of advanced IPC
• Message passing
• Semaphores
• Shared memory
IPC facility keys
•
•
•
•
•
UNIX has made the 3 categories of IPC as similar
as possible for programming convenience
The most (?) important similarity is the IPC key
Keys are numbers used to identify an IPC object
on a UNIX system
Much like a file name being used to identify files
Key allows IPC object to be shared by several
processes
Difference between keys and file
names
• Keys are not file names and carry less
meaning
• Actual key type is determined by
implementation, and defined by key_t in
<sys/types.h>
• UNIX uses a simple library funciton that
maps a file’s pathname to a key
– Routine is called ftok( )
IPC get operation
• With the get operation, a program uses a key
to
– Create an IPC, or,
– Gain access to an existing one
Mqid = msgget((key_t)0100, 0644|IPC_CREAT|IPC_EXCL);
Msg queue key
Non-neg id returned if successful
For semaphores: semget
For shared mem: shmget
Other IPC Operations
• Control operations
– Get status information
– Set control values
– Actual calls are msgctl, semctl, shmctl
• More specific operations to perform various
functions
– Do interesting work
– Called “IPC operations”
– For example, for message queues we have:
• Msgsend
• msgrcv
Status data structures
• When an IPC object is created, the system
also creates an IPC facility status structure
• This contains any administrative info assoc
with object
• There is one type of status structure for
messages, semaphores and shared mem
• However all 3 contain a common permission
structure, ipc_perm
Message passing
• A message is basically a sequence of
characters of bytes, not necessarily nullterminated
• One process creates a message queue using
msgget
• One a queue is established, a process with
the right permissions can put messages into it
with msgsnd
• Another process can then read this message
with msgrcv
Form of msgget
#include <sys/msg.h>
int msgget(key_t key, int permflags);
Permflags
• Determines the exact action perform by msgget
• Two constants are relevant here, defined in <sys/ipc.h>
• Can be used alone or ORed together
– IPC_CREAT
• Tells msgget to create a message queue for the value
key if one doesn't exist
• Message queue will not be overwritten if it already
exists
• If not set, then msgget returns id of existing
msgqueue, if exists
– IPC_EXCL
• If this and IPC_CREAT are both set, then only intend
to create new msgqueue
• Return -1 if already exists
Download