Powrót do listy plików
sem_lib.c
#include "sem_lib.h"
//uzyskanie od systemu identyfikatora semafora
//i nadanie semaforowi wartości początkowej jeden
int
init (int key, int what)
{
int retval;
//utworzenie semafora
if ((retval = semget (key, 1, 0666 | IPC_CREAT)) == -1)
{
perror ("[eee] błąd przy tworzeniu semafora");
exit (-1);
}
else
{
printf ("\n[iii] utworzono semafor");
//zainicjowanie semafora numer zero wartością argumentu "what"
if (semctl (retval, 0, SETVAL, what) == -1)
{
perror ("[eee] błąd przy zainicjowaniu semafora");
exit (-1);
}
printf ("\n[iii] zainicjowano semafor wartością [%i]", what);
//sleep (2);
}
return retval;
}
//funcja P - wejscie do sekcji krytycznej
void
P (int s, pid_t pid)
{
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = -1; //operacja P - dekrementowanie semafora
sb.sem_flg = SEM_UNDO;
//operacja na semaforze ma być automatycznie wycofana w razie śmierci procesu
printf ("\n\t\t wartość semafora [%i]", sem_val (s));
printf ("\t\t czekających [%i] ", sem_ile (s));
//proba dekrementowania semafora
//Proces zostanie uśpiony do chwili wykonania operacji
if (semop (s, &sb, 1) == -1)
{
perror ("[eee] błąd przy operacji P");
}
printf ("\n[+++][%i] jestem w sekcji krytycznej", pid);
printf ("\n\t\t wartość semafora [%i]", sem_val (s));
printf ("\t\t czekających [%i]\n", sem_ile (s));
return;
}
//funkcja V - opuszczanie sekcji krytycznej
void
V (int s, pid_t pid)
{
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = 1; //operacja V - inkrementowanie semafora
sb.sem_flg = SEM_UNDO;
//operacja na semaforze ma być automatycznie wycofana w razie śmierci procesu
printf ("\n\t\t wartość semafora [%i]", sem_val (s));
printf ("\t\t czekających [%i]", sem_ile (s));
//semop(int semid, struct sembuf *sops,)
if (semop (s, &sb, 1))
{
perror ("[eee] błąd przy operacji V");
}
else
{
printf ("\n[iii][%i] Inkrementacja semafora", pid);
printf ("\n\t\t wartość semafora [%i]", sem_val (s));
printf ("\t\t czekających [%i]\n", sem_ile (s));
}
return;
}
int
sem_val (int s)
{
int retval;
if ((retval = semctl (s, 0, GETVAL)) == -1)
{
perror ("[eee] błąd przy operacji GETVAL");
}
return retval;
}
int
sem_ile (int s)
{
int retval;
if ((retval = semctl (s, 0, GETNCNT)) == -1)
{
perror ("[eee] błąd przy operacji GETNCNT");
}
return retval;
}
void
sem_rm (int s)
{
if (semctl (s, 0, IPC_RMID) == -1)
{
perror ("[eee] błąd przy operacji IPC_RMID");
}
printf ("\n\n[iii] usunięto semafor [%i]\n", s);
}
składania pokolorowana przez
Code2HTML, v. 0.9.1
Materiały z Systemów Operacyjnych udostępnione zostały na zasadach licencji GPL w wersji 2.