Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
/*
* sem2.c
*
* Created on: Sep 21, 2013
* Author: roel
*/
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
#define MODE_NAMED_SEM 0
#define MODE_UNNAMED_FILE_MMAP 1
#define MODE_UNNAMED_SHM_MMAP 2
#define MODE_UNNAMED_TMPFS_FILE_MMAP 3
int main() {
sem_t * sem;
struct timespec time;
int fd;
void *map;
int err;
int mode;
mode = MODE_UNNAMED_TMPFS_FILE_MMAP;
if (mode == MODE_NAMED_SEM) {
sem = sem_open("/mysem", O_RDWR);
if (sem == SEM_FAILED ) {
printf("Failed to open map semaphore, %s \n", strerror(errno));
exit(1);
}
} else if (mode == MODE_UNNAMED_FILE_MMAP) {
fd = open("map", O_RDWR);
if (fd < 0) {
printf("Failed to open map file, %s \n", strerror(errno));
exit(1);
}
map = mmap(0, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED ) {
printf("Failed to open mmap, %s \n", strerror(errno));
exit(1);
}
sem = map;
} else if (mode == MODE_UNNAMED_SHM_MMAP) {
fd = shm_open("/mymap", O_RDWR, 0600);
if (fd < 0) {
printf("Failed to open map file, %s \n", strerror(errno));
exit(1);
}
map = mmap(0, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED ) {
printf("Failed to open mmap, %s \n", strerror(errno));
exit(1);
}
sem = map;
} else if (mode == MODE_UNNAMED_TMPFS_FILE_MMAP) {
fd = open("/tmp/map", O_RDWR);
if (fd < 0) {
printf("Failed to open map file, %s \n", strerror(errno));
exit(1);
}
map = mmap(0, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map == MAP_FAILED ) {
printf("Failed to open mmap, %s \n", strerror(errno));
exit(1);
}
sem = map;
}
printf("Posting semaphore\n");
clock_gettime(CLOCK_REALTIME, &time);
sem_post(sem);
printf("%ld \n", time.tv_nsec);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment