Download IPC - Shared Memory and Message Queues - System Programming | CS 241 and more Study notes Computer Science in PDF only on Docsity!
CS241 System Programming IPC – Shared Memory and Message
Queues (VI)^ Klara Nahrstedt^ Lecture 39^ 4/26/
Contents z^ Introduction to inter-process communicationfunctions z^ XSI Shared Memory^ –^ Access, attach, detach shared memory z^ XSI Message Queues^ –^ Create message queue, send and receive to/frommessage queues
POSIX: XSI InterprocessCommunication (IPC) z^ IPC is part of POSIX: XSI Extension z^ Origin in UNIX System V IPC z^ IPC includes^ –^ Message queues^ –^ Semaphore sets^ –^ Shared memory z^ We will go into detail on shared memory IPCmechanism and message queues
IPC Functions z^ Message Queues functions and their meaning^ –^ msgctl
/control/ – msgget /create or access/ – msgrcv /* receive message/ – msgsnd /send message*/
z^ Shared Memory functions and their meaning^ –^ shmat /attach memory to process/^ –^ shmctl /control/^ –^ shmdt /*detach memory from process /^ –^ shmget /create and initialize or access */
ftok Function z^ ftok^ function allows independent processes to derivethe same key based on a known pathname^ #include <sys/ipc.h>^ key_t ftok(const char *path, int id); z^ Example:^ if^ ((thekey
=^ ftok(“tmp/trouble.c”,1)
==^ (key_t)-1))
perror(“failed
to^ derive
key^ from
/tmp/trouble.c”);
Accessing IPC Resources from Shell^ z^ ipcs
command displays information aboutPOSIX:XCI IPC resources ipcs [-qms] [-a | -bcopt] z If no options are given,
ipcs^ gives all information on
message queues, share memory segments andsemaphore sets z If option^ –q
,^ -m^ and^ –s
are given, resources of
message queues, shared memory, and semaphoresets are shown, respectively.
Accessing a shared memory segment z^ Need function
shmget^
to access shared memory
segment^ –^ Function returns an identifier for the shared memorysegment associated with the key parameter^ –^ Function creates the shared segment if either the key isIPC_PRIVATE or shmflg&IPC_CREAT is non-zero and noshared segment or identifier are associated with key. #include^ <sys/shm.h> int^ shmget(key_t
key,^ size_t
size,^ int
shmflg);
Attaching and detaching a sharedmemory segment z^ Need function
shmat^ to attach shared memory segment
-^ Use structure
shmid^ for needed information
-^ Increment the value of
shm_nattach
for^ shmid
#include <sys/shm.h>^ void *shmat(int shmid, const void *shmaddr, int shmflg); z^ Need function
shmdt^ to detach shared memory segment
-^ Decrement
shm_nattch
in the structure
shmid
int^ shmdt(const
void^ *shmaddr); z^ Need function
shmctl^ to deallocate the shared memory
-^ The last process to detach the segment should deallocate the sharedmemory segment by calling
shmctl
Example (
detachandremove
function)
#include <stdio.h> #include <errno.h> #include <sys/shm.h>^ int detachandremove(int shmid,void *shmaddr){^ int error =0;^ if (shmdt(shmaddr) == -1) error = errno;^ if (shmctl(shmid, IPC_RMID, NULL) == -1) && !error) error =errno;^ if (!error) return 0;^ errno=error;^ return -1; }
Shared Memory Examples z^ Consider the following example (Program 15.5):^ –^ Parent and child process share a small memory segment^ –^ The child stores its byte count in the shared memory^ –^ The parent waits for the child to finish and then outputs thenumber of bytes received from each process along with thesum of these values^ –^ The parent creates the shared memory segment by usingIPC_PRIVATE – allows the memory to be shared with thechild^ –^ The parent does not access the shared memory until it hasdetected the termination of the child
Program 15.5 (Parent-ChildCommunication)^ if ((childpid = fork())==-1) {^ perror(“failed to create child process”);^ if (detachtoremove(id,sharedtotal) == -1)^ perror(“failed to destroy shared memory segment”); return 1; }^ if (childpid >0) fd = fd1;
/parent code/ else fd = fd2; while ((bytesread = readwrite(fd, STDOUT_FILENO)) > 0)^ totalbytes +=bytesread; if (childpid == 0) sharedtotal = totalbytes; return 0; /child code/ if (r_wait(NULL) == -1) perror(“failed to wait for child”); else …./ print information */ if (detachandremove(id, sharedtotal) == -1) {^ perror(“failed to destroy shared memory segment”), return 1; } return 0; }
POSIX:XSI Message Queues z^ Message queues^ –^ IPC mechanism^ z^ allows a process to send and receive messages from other processes. z^ Important data structures for message queues are in
sys/msg.h
z^ Major data structure is
msqid_ds struct ipc_perm msg_perm;/*oper.
permission structure */
msgqnum_t msg_qnum; /number of msg currently in queue/ msglen_t msg_qbytes; /max. bytes allowed in queue/ pid_t msg_lspid; /* process ID of msgsnd/ pid_t msg_lrpid; / process ID of msgrcv/ time_t msg_stime; / time
of last msgsnd/ time_t msg_rtime; / time of last msgrcv / time_t msg_ctime; / time of last msgctl */
Insert Message into queue z^ Need function
msgsnd^ to insert messages into the queue – Parameter msqid^ identifies the message queue – Parameter msgp^ points to a user-defined buffer that contains the message to besent – Parameter msgsz^ specifies the actual size of the message text – Parameter msgflg^ specifies actions to be taken under various conditions #include <sys/msg.h> int msgsnd(int msqid, const void msgp, size_t msgsz, intmsgflg); z^ User-defined message format struct mymsg{^ long mtype; / message type /^ char mtext[1]; /message text*/ } mymsg_t;
Protocol to send message (e.g., mymessage
) to a message queue
z^ Step 1: Allocate buffer
mbuf^ which is of type
mymsg_t
and^ size sizeof(mymsg_t) +strlen(mymessage) z Step 2: Copy
mymessage
into the^ mbuf->mtext
member z Step 3: Set message type in the
mbuf->mtype
member
z^ Step 4: Send the message z^ Step 5: Free
mbuf
Don’t forget to check for errors and to free mbuf if any erroroccurs