Screenplay: Sysprog: POSIX IPC¶
Virtual Memory, mmap()
¶
First, read
/etc/passwd
using regular file IODiscuss copy from/to kernel space
Basic
mmap()
demo: read/etc/passwd
by creating a mapping and only using memory access.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <assert.h>
int main()
{
int fd = open("/etc/passwd", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
struct stat stat;
int error = fstat(fd, &stat);
if (error) {
perror("fstat");
return 1;
}
void* addr = mmap(NULL, stat.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (addr == MAP_FAILED) {
perror("mmap");
return 1;
}
close(fd);
ssize_t nwritten = write(STDOUT_FILENO, addr, stat.st_size);
if (nwritten == -1) {
perror("write");
return 1;
}
assert(nwritten != 0);
return 0;
}
Give explanation of mappings
Discuss copy -> whiteboard sketch
Show
/proc/<pid>/maps
strace
to see how address space is preparedFile mappings vs. anonymous
POSIX Semaphores¶
Analogous to the shared memory demo above, this is a scenario where
two parties use post
and wait()
on a semaphore.
Create Semaphore¶
We create a semaphore with initial value 7 (7 wait
operations
without blocking).
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <stdio.h>
int main()
{
sem_t* sem = sem_open("meine-semaphore", O_CREAT|O_RDWR|O_EXCL, 0666, 7);
if (sem == SEM_FAILED) {
perror("sem_open");
return 1;
}
return 0;
}
Wait¶
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <stdio.h>
int main()
{
sem_t* sem = sem_open("meine-semaphore", O_RDWR);
if (sem == SEM_FAILED) {
perror("sem_open");
return 1;
}
int error = sem_wait(sem);
if (error) {
perror("sem_wait");
return 1;
}
return 0;
}
Post¶
#include <fcntl.h>
#include <sys/stat.h>
#include <semaphore.h>
#include <stdio.h>
int main()
{
sem_t* sem = sem_open("meine-semaphore", O_RDWR);
if (sem == SEM_FAILED) {
perror("sem_open");
return 1;
}
int error = sem_post(sem);
if (error) {
perror("sem_post");
return 1;
}
return 0;
}