File: semaphor.c

package info (click to toggle)
raidutils 0.0.6-23
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 10,840 kB
  • sloc: cpp: 39,794; ansic: 22,774; sh: 8,306; makefile: 19
file content (930 lines) | stat: -rw-r--r-- 24,666 bytes parent folder | download | duplicates (5)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
/* Copyright (c) 1996-2004, Adaptec Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of the Adaptec Corporation nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

//File - SEMAPHOR.C
//***************************************************************************
//
//Description:
//
//      This file contains function definitions to work with mutually
//exclusive semaphors in an OS independent manner.
//
//Author:
//Date:
//
//Editors:
//
//Remarks:
//
//      NOTE NOTE!
//
//      The method of using file read and write locks to know if you are the
//      only one who has the semaphore open will not work if multiple threads
//      in a single process open the same named semaphore.  This is because a
//      file lock is per process not per thread.  So, one thread could change
//      another thread's read lock to a write lock and not know it.
//
//      Currently at DPT, threads share the same semaphore handle, so it is
//      not a problem.
//
//***************************************************************************


/* Include Files ------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include "osd_util.h"

/*
 * Some Unixes require a fourth parameter to semctl of type 'union semun',
 * while other variants are more flexible but also don't define that type.
 *
 * To make matters even more interesting, SCO UNIX 3.2.4.2 defines it, but SCO
 * OpenServer doesn't.  Since we still need to support 3.2.4.2, if compiling
 * on OpenServer add -D_DPT_DEFINE_SEMUN=1 to your makefile.
 *
 * Also, for new operating systems, it is preferrable to add the above define
 * in your makefile rather than add the OS-define below in the code.
 */

#if !defined(_DPT_DEFINE_SEMUN)

#if defined(_DPT_FREE_BSD) || defined(_DPT_BSDI) 

#define _DPT_DEFINE_SEMUN 0 
#else
#define _DPT_DEFINE_SEMUN 1 
#endif
#endif


/* Definitions - Defines & Constants ----------------------------------------*/

#define MAX_LOCAL_SEM       10
#define MAX_SEM_NAME_LEN    80  /* including 5 characters added here "/tmp/" */

/* Definitions - Structures -------------------------------------------------*/

typedef struct {
    char semName[MAX_SEM_NAME_LEN];
    int handle;
    int semID;
    int index;
} DPT_Semaphore_S;

#if _DPT_DEFINE_SEMUN != 0
union semun {
    int val;
};
#endif

/* Global Variables ---------------------------------------------------------*/

static char LocalSemaphoreName[MAX_SEM_NAME_LEN] = "";
static int LocalSemaphoreInUse[MAX_LOCAL_SEM];
static int LocalSemID = -1;

extern int Verbose;

/* Function Prototypes ------------------------------------------------------*/


//Function - privateCreateNamedSemaphore()  - start
//===========================================================================
//
//Description:
//
//  This function creates a semaphore to provide mutually exclusive
//or event-type access to an application resource.
//
//Parameters:
//
//Return Value:
//
//  NULL        = Failure, unable to create a new semaphore
//  Non-zero    = Success, handle to the newly created semaphore
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//  A helper function for other routines in this file.  It is internal to
//  this file and should not be called from outside.
//
//---------------------------------------------------------------------------

static SEMAPHORE_T privateCreateNamedSemaphore(char *name, int initialValue)
{
    DPT_Semaphore_S *rtnVal;
    int iAmFirst = 0;
    key_t key;
    union semun arg;
    struct flock lock;

    rtnVal = (DPT_Semaphore_S *) malloc(sizeof(DPT_Semaphore_S));

    if (rtnVal != NULL) {

        // Open the file so we can get file lock on it and create if it
        // doesn't exist

        rtnVal->handle = open(name, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG);
        if (rtnVal->handle < 0) {
            free(rtnVal);
            rtnVal = NULL;
        }
    }

    if (rtnVal != NULL) {

        strcpy(rtnVal->semName, name);
        rtnVal->index = 0;

        // See if anyone else is using the semaphore.  If anyone else is using
        // it, they will have a read lock and I wouldn't be able to get the
        // write lock without waiting.  If someone else is using it, wait for
        // them and get a read lock.  If I exit this code block without error,
        // I'll have some kind of lock

        lock.l_type = F_WRLCK;
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;
        lock.l_len = 0;     // till end-of-file

        if (fcntl(rtnVal->handle, F_SETLK, &lock) != 0) {
            if (errno != EACCES && errno != EAGAIN) {
                close(rtnVal->handle);
                free(rtnVal);
                rtnVal = NULL;
            } else {
                // Let others know I'm using the semaphore

                lock.l_type = F_RDLCK;

                if (fcntl(rtnVal->handle, F_SETLKW, &lock) != 0) {
                    close(rtnVal->handle);
                    free(rtnVal);
                    rtnVal = NULL;
                }
            }
        } else {
            iAmFirst = 1;
        }
    }

    lock.l_type = F_UNLCK;  // if anything goes wrong I need to unlock

    if (rtnVal != NULL) {

        // Get the key for the file to use to get the actual semaphore

        key = ftok(rtnVal->semName, 'D');

        if (key == (key_t) -1) {
            fcntl(rtnVal->handle, F_SETLKW, &lock);
            close(rtnVal->handle);
            free(rtnVal);
            rtnVal = NULL;
        }
    }

    if (rtnVal != NULL) {

        // Get the semaphore handle and create it if it isn't already there.
        // Let other processes access it as well

        rtnVal->semID = semget(key, 1, IPC_CREAT | S_IRWXU | S_IRWXG);

        if (rtnVal->semID == -1) {
            if (Verbose)
                perror("\nprivateCreateNamedSemaphore");

            fcntl(rtnVal->handle, F_SETLKW, &lock);
            close(rtnVal->handle);
            free(rtnVal);
            rtnVal = NULL;
        }
    }

    // At this point, if we are the first (and only) person to get the
    // semaphore, initialize its start value

    if (rtnVal != NULL && iAmFirst) {

        arg.val = initialValue;

        if (semctl(rtnVal->semID, rtnVal->index, SETVAL, arg) != 0) {
            // note arg is unused for IPC_RMID
            semctl(rtnVal->semID, 0, IPC_RMID, arg);
            fcntl(rtnVal->handle, F_SETLKW, &lock);
            close(rtnVal->handle);
            free(rtnVal);
            rtnVal = NULL;
        } else {
            // Release the Write lock and change to a read lock

            lock.l_type = F_RDLCK;

            if (fcntl(rtnVal->handle, F_SETLK, &lock) != 0) {
                // note arg is unused for IPC_RMID
                semctl(rtnVal->semID, 0, IPC_RMID, arg);
                close(rtnVal->handle);
                free(rtnVal);
                rtnVal = NULL;
            }
        }
    }

    return((SEMAPHORE_T) rtnVal);
}
//privateCreateNamedSemaphore() - end




//Function - privateCreateUnnamedSemaphore()  - start
//===========================================================================
//
//Description:
//
//  This function creates a semaphore to provide mutually exclusive
//or event-type access to an application resource.
//
//Parameters:
//
//Return Value:
//
//  NULL        = Failure, unable to create a new semaphore
//  Non-zero    = Success, handle to the newly created semaphore
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//  A helper function for other routines in this file.  It is internal to
//  this file and should not be called from outside.
//
//---------------------------------------------------------------------------

static SEMAPHORE_T privateCreateUnnamedSemaphore(int initialValue)
{
    DPT_Semaphore_S *rtnVal;
    union semun arg;
    int i;

    if (LocalSemID == -1) {

        // If we can't get the program name or create the file, go with the
        // private semaphore instead of a key based on ftok()

        key_t key = IPC_PRIVATE;

        if (LocalSemaphoreName[0] == '\0') {

            extern char **Argv;
            char *name;
            int handle;

            name = Argv[0];

            if (name != NULL) {
                name = strrchr(name, '/');
                if (name != NULL)
                    name++;
                else
                    name = Argv[0];
            }

            if (name != NULL) {
                strcpy(LocalSemaphoreName, "/tmp/");
                strcat(LocalSemaphoreName, name);
                strcat(LocalSemaphoreName,"_unnamed");

                handle = open(LocalSemaphoreName, O_CREAT | O_RDWR, 0);

                if (handle < 0)
                    LocalSemaphoreName[0] = '\0';
                else {
                    close(handle);
                    key = ftok(LocalSemaphoreName, 'D');

                    if (key == (key_t) -1) {
                        LocalSemaphoreName[0] = '\0';
                        key = IPC_PRIVATE;
                    }
                }
            }
        }


        // Get the semaphore ID for the block of unnamed semaphores

        LocalSemID = semget(key, MAX_LOCAL_SEM, IPC_CREAT);

        if (LocalSemID == -1) {

            if (Verbose)
                perror("\nprivateCreateUnnamedSemaphore");

            return NULL;
        }

        for (i = 0; i < MAX_LOCAL_SEM; i++)
            LocalSemaphoreInUse[i] = 0;
    }

    for (i = 0; i < MAX_LOCAL_SEM && LocalSemaphoreInUse[i]; i++) {
        // Nothing
    }

    if (i == MAX_LOCAL_SEM) {

        if (Verbose)
            printf("\nToo many unnamed semaphores!");

        return NULL;
    }

    rtnVal = (DPT_Semaphore_S *) malloc(sizeof(DPT_Semaphore_S));

    if (rtnVal != NULL) {

        LocalSemaphoreInUse[i] = 1;

        rtnVal->semName[0] = '\0';
        rtnVal->semID = LocalSemID;
        rtnVal->handle = -1;
        rtnVal->index = i;
    }

    // Initialize the semaphore's start value

    if (rtnVal != NULL) {

        arg.val = initialValue;

        if (semctl(LocalSemID, rtnVal->index, SETVAL, arg) != 0) {
            LocalSemaphoreInUse[rtnVal->index] = 0;
            free(rtnVal);
            rtnVal = NULL;
        }
    }

    return((SEMAPHORE_T) rtnVal);
}
//privateCreateUnnamedSemaphore() - end




//Function - osdCreateSemaphore()  - start
//===========================================================================
//
//Description:
//
//      This function creates a semaphore to provide mutually exclusive
//access to an application resource.
//
//Parameters:
//
//Return Value:
//
//  NULL        = Failure, unable to create a new semaphore
//  Non-zero    = Success, handle to the newly created semaphore
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//---------------------------------------------------------------------------

SEMAPHORE_T osdCreateSemaphore()
{
    SEMAPHORE_T rtnVal;

    rtnVal = privateCreateUnnamedSemaphore(0);

    if (Verbose)
        printf("\nosdCreateSemaphore   : Rtn = %lx", (unsigned long)rtnVal);

    return(rtnVal);
}
//osdCreateSemaphore() - end




//Function - osdCreateNamedSemaphore - start
//===========================================================================
//
//Description: creates a named semaphore so outside processes can gain access
//                  to it
//
//
//Parameters:
//
//Return Value:
//
//  NULL        = Failure, unable to create a new semaphore
//  Non-zero    = Success, handle to the newly created semaphore
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------

SEMAPHORE_T osdCreateNamedSemaphore(char *name)
{
    char temp[MAX_SEM_NAME_LEN];
    SEMAPHORE_T rtnVal;

    strcpy(temp, "/tmp/");
    strcat(temp, name);

    rtnVal = privateCreateNamedSemaphore(temp, 0);

    if (Verbose)
        printf("\nosdCreateNamedSemaphore   : Rtn = %lx", (unsigned long)rtnVal);

    return(rtnVal);
}
//osdCreateNamedSemaphore() - end





//Function - osdDestroySemaphore() - start
//===========================================================================
//
//Description:
//
//  This function destroys the specified mutually exclusive
//semaphore.
//
//Parameters:
//
//    semHandle = Handle to the semaphore to be destroyed
//
//Return Value:
//
//  0       = Success, semaphore destroyed
//  non-zero    = Failure, semaphore not destroyed
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//---------------------------------------------------------------------------

uSHORT osdDestroySemaphore(SEMAPHORE_T semHandle)
{
    DPT_Semaphore_S *sem = (DPT_Semaphore_S *) semHandle;
    uSHORT rtnVal = 0;

    if (sem->semName[0] == '\0') {

        int i;

        // It's an unnamed semaphore, set the index in the block to not-in-use

        if (sem->index < MAX_LOCAL_SEM)
            LocalSemaphoreInUse[sem->index] = 0;

        // If all unnamed semaphores are now not-in-use, give back the
        // semaphore block

        for (i = 0; i < MAX_LOCAL_SEM && !LocalSemaphoreInUse[i]; i++) {
            // Nothing
        }

        if (i == MAX_LOCAL_SEM) {

            union semun arg;

            // note arg is unused for IPC_RMID
            arg.val = 0;
            rtnVal = semctl(LocalSemID, 0, IPC_RMID, arg) != 0;

            if (rtnVal == 0) {
                LocalSemID = -1;
                unlink(LocalSemaphoreName);
            }
        }

    } else {

        // It's a nammed semaphore

        struct flock lock;

        // See if anyone else is using the semaphore.  If anyone else is using
        // it, they will have a read lock and I wouldn't be able to change my
        // lock to a write lock without waiting.

        lock.l_type = F_WRLCK;
        lock.l_whence = SEEK_SET;
        lock.l_start = 0;
        lock.l_len = 0;     // till end-of-file

        if (fcntl(sem->handle, F_SETLK, &lock) == 0) {
            union semun arg;

            // I got the write lock; I must be the last one using the
            // semaphore. Delete it and the file associated with it.

            // note arg is unused for IPC_RMID
            arg.val = 0;
            semctl(sem->semID, 0, IPC_RMID, arg);
            unlink(sem->semName);
        }
        else
        {
            // I didn't get the write lock; someone else has the semaphore
            // open.  Release my read lock now that I'm not using the
            // semaphore any more.

            lock.l_type = F_UNLCK;

            rtnVal = fcntl(sem->handle, F_SETLKW, &lock) != 0;
        }

        close(sem->handle);
    }

    if (rtnVal == 0)
        free(sem);

    if (Verbose)
        printf("\nosdDestroySemaphore   : Rtn = %x", rtnVal);

    return(rtnVal);
}
//osdDestroySemaphore() - end




//Function - osdRequestSemaphore() - start
//===========================================================================
//
//Description:
//
//      This function requests access to the specified mutually
//exclusive semaphore.
//
//Parameters:
//
//   semHandle  = Handle to the semaphore to request access
//   timeout    = # of milliseconds to wait for the semaphore
//
//Return Value:
//
//  0           = Access granted
//  Non-zero    = Access denied (timed out)
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//---------------------------------------------------------------------------

static void semaphoreSignalHandler(int sig)
{
    // do nothing, we'll get an error back from semop()
    sig = sig;
}

uLONG osdRequestSemaphore(SEMAPHORE_T semHandle, uLONG timeout)
{
    DPT_Semaphore_S *sem = (DPT_Semaphore_S *) semHandle;
    uLONG rtnVal = 0;
    int resetAction = 0;
    unsigned int oldAlarm;
    unsigned int waited;
    struct sembuf semOps[2];
    struct sigaction newSig;
    struct sigaction oldSig;

    // Set up for two operations on this semaphore.  First wait for it to
    // go to 0, and then set it to 1

    semOps[0].sem_num = sem->index;
    semOps[0].sem_op = 0;
    semOps[0].sem_flg = 0;
    semOps[1].sem_num = sem->index;
    semOps[1].sem_op = 1;
    semOps[1].sem_flg = 0;

    // If they don't want to wait, set the appropriate flag and change the
    // timeout variable as a signal to code below not to set an alarm

    if (timeout == 0) {
        semOps[0].sem_flg |= IPC_NOWAIT;
        semOps[1].sem_flg |= IPC_NOWAIT;

        timeout = 0xffffffff;
    }

    // Set up an alarm signal to timeout our semop() call unless the user
    // asked for an "infinite" timeout by sending FFFFFFFF or we are asked
    // not to wait at all.
    //
    // Remember how much time was remaining on old Alarm, if any, and reset
    // signal handler to point to ours for the duration of our wait.  Then
    // set an alarm for our timeout.
    //

    if (timeout != 0xffffffff)
    {
        // Convert timeout to seconds and round up

        timeout = (timeout + 999) / 1000;

        memset(&newSig, 0, sizeof(newSig));
        newSig.sa_handler = semaphoreSignalHandler;

        oldAlarm = alarm(0);
        rtnVal = (sigaction (SIGALRM, &newSig, &oldSig) != 0);

        if (rtnVal == 0) {
            resetAction = 1;
            alarm((unsigned int) timeout);
        } else {
            // try to set back to their original alarm value remaining
            alarm(oldAlarm);
        }
    }

    // Now wait for the semaphore

    if (rtnVal == 0) {
        rtnVal = (semop(sem->semID, semOps, 2) != 0);
    }

    // If we set an alarm above, adjust things

    if (timeout != 0xffffffff) {
        // Calculate how much time we were waiting and if necessary, restart
        // the Alarm for the remaining time from the caller's original alarm.
        // If we waited longer than they had remaining when we started, raise
        // the signal after replacing their handler so they'll get it
        // immediately

        waited = (unsigned int) timeout - alarm(0);

        if (resetAction) {
            sigaction (SIGALRM, &oldSig, NULL);
        }

        if (oldAlarm != 0) {
            if (oldAlarm > waited) {
                alarm(oldAlarm - waited);
            } else {
                raise(SIGALRM);
            }
        }
    }

    if (Verbose)
        printf("\nosdRequestSemaphore   : Rtn = %lx\n", rtnVal);

    return(rtnVal);
}
//osdRequestSemaphore() - end




//Function - osdReleaseSemaphore() - start
//===========================================================================
//
//Description:
//
//      This function relinquishes control of the specified mutually
//exclusive semaphore.
//
//Parameters:
//
//   semHandle  = Handle to the semaphore to be released.
//
//Return Value:
//
//  0           = Success, the semaphore has been released
//  Non-zero    = Failure, unable to release the semaphore
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//---------------------------------------------------------------------------

uSHORT osdReleaseSemaphore(SEMAPHORE_T semHandle)
{
    DPT_Semaphore_S *sem = (DPT_Semaphore_S *) semHandle;
    uSHORT rtnVal = 1;
    struct sembuf semOp;

    // Set Up To Decrement The Semaphore Value By 1

    semOp.sem_num = sem->index;
    semOp.sem_op = -1;
    semOp.sem_flg = IPC_NOWAIT;

    rtnVal = semop(sem->semID, &semOp, 1) != 0;

    if (rtnVal && errno == EAGAIN) {
        // Ignore errors caused by releasing the semaphore too many times.
        // This can happen legitimately through osdSignalEventSemaphore().

        rtnVal = 0;
    }

    if (Verbose)
        printf("\nosdReleaseSemaphore   : Rtn = %x\n", rtnVal);

    return(rtnVal);
}
//osdReleaseSemaphore() - end




//Function - osdResetEventSemaphore - start
//===========================================================================
//
//Description: resets the event to the unhappened state
//
//
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------

uLONG osdResetEventSemaphore(SEMAPHORE_T semHandle)
{
    semHandle = semHandle;
    return 0;
}
//osdResetEventSemaphore() - end




//Function - osdSignalEventSemaphore - start
//===========================================================================
//
//Description: set this event to happened
//
//
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------

uLONG osdSignalEventSemaphore(SEMAPHORE_T semHandle)
{
    return (uLONG) osdReleaseSemaphore(semHandle);
}
//osdSignalEventSemaphore() - end




//Function - osdWaitForEventSemaphore - start
//===========================================================================
//
//Description: waits for an event semaphore to be signaled either forever
//                  or until the number of milliseconds has expired
//
//
//
//Parameters:
//
//Return Value:  0 success
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------

uLONG osdWaitForEventSemaphore(SEMAPHORE_T semHandle, uLONG timeout)
{
    return osdRequestSemaphore(semHandle, timeout);
}
//osdWaitForEventSemaphore() - end




//Function - osdCreateEventSemaphore()  - start
//===========================================================================
//
//Description:
//
//  This function creates an event semaphore to allow synchronization between
//      threads
//
//
//Parameters:
//
//Return Value:
//
//  NULL    = Failure, unable to create a new semaphore
//  Non-zero    = Success, handle to the newly created semaphore
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//---------------------------------------------------------------------------

SEMAPHORE_T osdCreateEventSemaphore()
{
    SEMAPHORE_T rtnVal;

    rtnVal = privateCreateUnnamedSemaphore(1);

    if (Verbose)
        printf("\nosdCreateEventSemaphore   : Rtn = %lx", (unsigned long)rtnVal);

    return(rtnVal);
}
//osdCreateEventSemaphore() - end




//Function - osdCreateNamedEventSemaphore - start
//===========================================================================
//
//  This function creates a named event semaphore to allow synchronization
//      between threads and processes
//
//
//Parameters:
//
//Return Value:
//
//Global Variables Affected:
//
//Remarks: (Side effects, Assumptions, Warnings...)
//
//
//---------------------------------------------------------------------------

SEMAPHORE_T osdCreateNamedEventSemaphore(char *name)
{
    char temp[MAX_SEM_NAME_LEN];
    SEMAPHORE_T rtnVal;

    strcpy(temp, "/tmp/");
    strcat(temp, name);

    rtnVal = privateCreateNamedSemaphore(temp, 1);

    if (Verbose)
        printf("\nosdCreateNamedEventSemaphore   : Rtn = %lx", (unsigned long)rtnVal);

    return(rtnVal);
}
//osdCreateNamedEventSemaphore() - end