Introduction
Introduction Statistics Contact Development Disclaimer Help
<- Back
A minimal example of C's syscall mmap() to share memory between processes
=========================================================================
Recently I decided to add a feature to bsleep:
My idea was to show the last button pressed (other than 'b', which would
interrupt the sleep).
The problem to overcome was the following:
When fork() is used, parent and child no longer can access each others
variables.
Since it's the parent-process reading the button pressed, while the child
is printing the update. Therefore the child needs to read the character
from the parent process.
Using mmap() I added a pointer to 1 byte of memory which both processes
can access. It stores the character of the last button pressed.
As a result bsleep has become a minimal example of:
- how to fork a process in C
- how to exchange data between parent and child process using mmap()
git clone git://kroovy.de/bsleep
Build dependencies
- C compiler
- libc
#define _POSIX_SOURCE
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
int
main(void)
{
int i;
char *shmem = mmap(NULL, sizeof(char), PROT_READ | PROT_WRITE, MAP_SH…
pid_t pid = fork();
if (pid == 0) {
/* CHILD */
for (i=1;;i++) {
printf("\r[ press 'b' to interrupt: %ds ] [ '%c' was pressed …
fflush(stdout);
sleep(1);
}
} else {
/* PARENT */
system("/bin/stty raw -echo");
while ((*shmem = getchar()) != 'b');
kill(pid, SIGKILL);
system("/bin/stty cooked echo");
printf("\n");
}
}
In the near future I will consider adding error-handling and will have a
look at pagesize. It might be a good idea to let mmap claim a page-aligned
amount of bytes. Not sure at this point.
You are viewing proxied material from kroovy.de. The copyright of proxied material belongs to its original authors. Any comments or complaints in relation to proxied material should be directed to the original authors of the content concerned. Please see the disclaimer for more details.