diff options
Diffstat (limited to 'schulung_tools/ipc_shm/shm.c')
| -rw-r--r-- | schulung_tools/ipc_shm/shm.c | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/schulung_tools/ipc_shm/shm.c b/schulung_tools/ipc_shm/shm.c new file mode 100644 index 0000000..777fe79 --- /dev/null +++ b/schulung_tools/ipc_shm/shm.c @@ -0,0 +1,73 @@ +#include <stdio.h> +#include <stdlib.h> +#include <pthread.h> +#include <fcntl.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/mman.h> +#include "shm.h" + +#define SHARE_NAME "/ipc.shm" + +/* open and return a pointer to shared data */ +struct share_data *get_share(void) +{ + struct share_data *data; + int fd; + + fd = shm_open(SHARE_NAME, O_RDWR, 0); + if (fd == -1) + return NULL; + + data = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ | PROT_WRITE, + MAP_SHARED, fd, 0); + if (data == MAP_FAILED) { + close(fd); + return NULL; + } + + close(fd); + + return data; +} + +/* initialize shared data */ +void init_share(struct share_data *data) +{ + pthread_mutexattr_t mattr; + pthread_condattr_t cattr; + + pthread_mutexattr_init(&mattr); + pthread_mutexattr_setprotocol(&mattr, PTHREAD_PRIO_INHERIT); + pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); + pthread_mutexattr_setrobust(&mattr, PTHREAD_MUTEX_ROBUST); + pthread_mutex_init(&data->m, &mattr); + + pthread_condattr_init(&cattr); + pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED); + pthread_cond_init(&data->c, &cattr); +} + +/* create a zero'd out file of size 1 page */ +int create_share(void) +{ + int ret; + int fd; + + fd = shm_open(SHARE_NAME, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR); + if (fd == -1) + return -1; + + ret = ftruncate(fd, sysconf(_SC_PAGESIZE)); + + close(fd); + + return ret; +} + +/* remove the share */ +void remove_share(void) +{ + shm_unlink(SHARE_NAME); +} |
