Lab 4 — System V IPC: Shared Memory & Message Queues
CMPS 3600 • Fall 2025
CMPS 3600 • Fall 2025
This lab introduces two System V IPC mechanisms: shared memory and message queues. You will write a parent/child program where the parent sends an integer via shared memory and a string via a message queue.
$ cd ~
$ cd cs3600
$ ./lab-start.sh
$ cd 4
$ cp /home/fac/dfanucchi/public_html/cs3600/examples/4/*.c .
$ cp /home/fac/dfanucchi/public_html/cs3600/examples/4/Makefile .
$ cp /home/fac/dfanucchi/public_html/cs3600/examples/4/cleanipc.sh .
Read each example, compile, and run it. When comfortable, begin dflab4.c
.
$ ./cleanipc.sh <username> #this is a script that should do the clean up for you
# to view and remove your IPC objects manually, use the following commands:
$ ipcs -m # shared memory
$ ipcs -q # message queues
$ ipcrm -m <shmid>
$ ipcrm -q <msqid>
dflab4.c
)Create the dflab4.c file, it is not included this week.
# this is not an exhaustive list, you need to list the remaining headers
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/shm.h>
fork()
foo
:
$ cd ~/cs3600/4
$ touch foo
Use ftok("foo", 17)
.log
file for writing (child will write; open before fork()
).0
.key_t ipckey = ftok("foo", 17);
int shmid = shmget(ipckey, sizeof(int), IPC_CREAT | 0666);
int *shared = (int*)shmat(shmid, NULL, 0);
*shared = 0;
struct msg { long mtype; char text[128]; };
int msqid = msgget(ipckey, IPC_CREAT | 0666);
fork()
*shared != 0
(with a small sleep):
while (*shared == 0) {
usleep(4250); /* 4.25ms */
}
log
.msgrcv()
for a word from parent; write it to log
.log
, detach from shared memory, exit(0)
.
wait()
.write(1, "Enter a 2-digit number: ", 24);
char buf[128]; memset(buf, 0, sizeof(buf));
read(0, buf, 4); // read up to 4 chars
int num = atoi(buf);
*shared = num;
#define BUFSIZE 256)
so it can safely hold
both the number and the word you’ll read from the user. Always memset()
the buffer before reuse.msgsnd()
to the queue.wait(&status)
to reap the child; print exit status.shmdt(shared)
, shmctl(shmid, IPC_RMID, 0)
, msgctl(msqid, IPC_RMID, 0)
.shmat()
is unnecessary.$ make
$ ./dflab4
Enter a two-digit number: 75
Enter a word: Linuxize
Child exited with status code 0
$ cat log
75
Linuxize
myinput
)myinput
# myinput
83
System-V
$ ./dflab4 < myinput
$ cat log
83
System-V
read()
may consume bytes from the next line. Adjust the read count and/or clear the buffer each time.strace
(IPC only)$ strace -f -e trace=ipc ./dflab4 < myinput
shmget(0x1102af98, 4, IPC_CREAT|0666) = 911605760
shmat(911605760, 0, 0) = 0x7fac33f01000
msgget(0x1102af98, IPC_CREAT|0666) = 297172992
Process 9356 attached
[pid 9355] msgsnd(297172992, {1, "System-V\n..."}, 112, 0) = 0
[pid 9356] msgrcv(297172992, {1, "System-V\n..."}, 112, 0, 0) = 112
[pid 9356] shmdt(0x7fac33f01000) = 0
--- SIGCHLD (Child exited) @ 0 (0) ---
shmdt(0x7fac33f01000) = 0
msgctl(297172992, IPC_RMID, 0) = 0
shmctl(911605760, IPC_RMID, 0) = 0
dflab4.c
Makefile
foo
myinput