summaryrefslogtreecommitdiff
path: root/schulung_tools/ipc_shm/shm.c
blob: 777fe799621ea40e8e9490389b54cf84cc803316 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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);
}