-
Notifications
You must be signed in to change notification settings - Fork 0
/
TP6.c
74 lines (69 loc) · 2.12 KB
/
TP6.c
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
74
/*
* TP6.c
*
* Created on: 1 mars 2016
* Author: Quincy
*/
#include <stdio.h> /* printf */
#include <stdlib.h> /* system, NULL, EXIT_FAILURE, EXIT_SUCCESS */
#include <sys/mman.h> /* mmap, msync, shm_open */
#include <fcntl.h> /* open */
#include <sys/stat.h> /* fstat */
#include <unistd.h> /* ftruncate */
#include <semaphore.h> /* sem_t, sem_open */
#include <sys/types.h> /* chmod, fchmod */
#include <sys/stat.h> /* umask */
struct Rendezvous
{
int value;
sem_t vide;
sem_t plein;
};
int main (int argc, char* argv[])
{
const char* semaphoreName = "SemaphoreSHM3";
struct Rendezvous* rdv; //Pointer points to the memory created by mmap to be used for Rendezvous
int memId = shm_open(semaphoreName, O_CREAT|O_RDWR, 0666);
if( memId<=0 )
{
perror("[1]shm_open() error");
exit(-1);
}
printf("[1]shm_open() created shared memory with id %d\n", memId);
//Problem on MAC with 2nd execution of ftruncate
//Check http://stackoverflow.com/questions/25502229/ftruncate-not-working-on-posix-shared-memory-in-mac-os-x
struct stat mapstat;
if (-1 != fstat(memId, &mapstat) && mapstat.st_size == 0)
{
if ( ftruncate(memId, sizeof(rdv)) < 0 )
{
perror("[1]ftruncate() error");
exit(-1);
}
}
printf("[1]ftruncate() shared memory to %lu\n", sizeof(rdv));
rdv = mmap(NULL, sizeof(rdv), PROT_READ|PROT_WRITE, MAP_SHARED, memId, 0);
if(rdv==MAP_FAILED)
{
perror("[1]Map failed");
exit(-1);
}
printf("[1]mmap() created successful\n");
rdv->value = 0;
sem_init(&rdv->vide, 1, 1); //This does not work on MAC
printf("[1]sem_init(&rdv->vide, 1, 1) executed\n");
sem_init(&rdv->plein, 1, 0);
printf("[1]sem_init(&rdv->plein, 1, 0) executed\n");
//rdv->vide = *sem_open("Rdv_Vide", O_CREAT|O_EXCL, S_IWGRP|S_IWOTH, 1);
//rdv->plein = *sem_open("Rdv_Plein", O_CREAT|O_EXCL, S_IWGRP|S_IWOTH, 0);
while(1)
{
sem_wait(&rdv->vide); //If not zero, block
printf("[1]Rendezvous.value after sem_wait()=%d\n", rdv->value);
rdv->value = rand()%100;
printf("[1]Changed value=%d\n", rdv->value);
sem_post(&rdv->plein);
printf("[1]Rendezvous.value after sem_post()=%d\n", rdv->value);
sleep(1);
}
}