Maked minor changes to Semaphore interface
[fmail.git] / src / posix-sem.cpp
blob22aae8483344429e6495e6d3fe281e98ea3fd0c5
1 /*
2 libfmail: Semaphore class
4 Copyright (C) 2007 Carlos Daniel Ruvalcaba Valenzuela <clsdaniel@gmail.com>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include <stdio.h>
22 #include <string.h>
23 #include <malloc.h>
25 #include <semaphore.h>
26 #include <libfmail/semaphore.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
32 struct _ossem{
33 sem_t *sem;
36 /* TODO: Add support for shared semaphores */
37 Semaphore::Semaphore(int value, int shared, char *key){
38 this->os_sem = (OSSem*)malloc(sizeof(OSSem));
39 this->sem_shared = shared;
41 this->sem_name = NULL;
42 if (key != NULL){
43 this->sem_name = (char*)malloc(strlen(key)+1);
44 strcpy(this->sem_name, key);
47 if (shared){
48 this->os_sem->sem = sem_open(key, O_CREAT);
49 }else{
50 this->os_sem->sem = (sem_t*)malloc(sizeof(sem_t));
51 sem_init(this->os_sem->sem, 0, value);
54 Semaphore::~Semaphore(){
55 if (sem_shared){
56 sem_close(os_sem->sem);
57 sem_unlink(sem_name);
58 free(sem_name);
59 }else{
60 sem_destroy(os_sem->sem);
61 free(os_sem->sem);
63 free(os_sem);
66 int Semaphore::TryWait(){
67 return sem_trywait(os_sem->sem);
70 int Semaphore::Wait(){
71 return sem_wait(os_sem->sem);
74 int Semaphore::Post(){
75 return sem_post(os_sem->sem);
78 int Semaphore::getValue(int *val){
79 return sem_getvalue(os_sem->sem, val);