Skip to content

Instantly share code, notes, and snippets.

@seberm
Created April 24, 2012 08:25
Show Gist options
  • Save seberm/2477868 to your computer and use it in GitHub Desktop.
Save seberm/2477868 to your computer and use it in GitHub Desktop.
Pouziti semaforu a shm
CC=gcc
CFLAGS=-pthread -lrt -std=gnu99
sem: sem.c
clean:
rm -f sem
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
const char* name = "/jmeno";
sem_t mutex;
void die(const char *msg) {
perror(msg);
exit(1);
}
void reader(int *s) {
printf("data: %d\n", *s);
sem_wait(&mutex);
printf("reading old....\n");
int x = 5;
printf("writing... %d\n", x);
*s = x;
sleep(3);
sem_post(&mutex);
exit(10);
}
int main () {
// inicializace semaforu
// 1 - bude na zacatku odemceny
// 0 - bude moci byt sdileny mezi procesy
if (sem_init(&mutex, 1, 1))
die("nepovedlo se inicializovat semafor");
int fd = shm_open(name, O_RDWR|O_CREAT, 0600);
if (fd < 0)
die("nepovedlo se otevreni");
if (ftruncate(fd, sizeof(int)))
die("truncate...");
int *shared;
shared = mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (shared == MAP_FAILED)
die("mmap failed ");
printf("hodnota pameti: %d\n", *shared);
pid_t pid = fork();
switch (pid) {
case 0:
reader(shared);
break;
case -1:
die("nepovedlo se vytvorit potomka");
break;
default:
printf("rodicak...\n");
// rodic
};
int stat;
waitpid(pid, &stat, 0);
printf("potomek exiting.... <-> %d\n", stat);
sem_wait(&mutex);
printf("hodnota pameti po ukonceni potomka: %d\n", *shared);
*shared = 5500;
printf("hodnota pameti nova: %d\n", *shared);
sem_post(&mutex);
printf("rodic exiting\n");
if (shm_unlink(name) < 0)
die("nepovedlo se smazat sdilenou pamet");
// musime zavrit semafor
if (sem_destroy(&mutex))
die("nepovedlo se smazat semafor");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment