-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsem.c
1066 lines (889 loc) · 27.4 KB
/
msem.c
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
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//#define _JDL_NO_PRINT_LOCATION
#define _JDL_NO_PRINT_DEBUG
#define _JDL_NO_PRINT_WARN
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <limits.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#include <j/time.h>
#include <j/file.h>
#include <j/shell.h>
#include <j/debug.h>
#include "msem.h"
extern int errno;
/*
* After Steven's 3-member semaphore set implementation.
*
* Create a set of 3 semaphores:
*/
/* [0]: The actual semaphore value. */
#define SEMAPHORE 0
/* [1]: The process counter. */
#define PROCESSES 1
/* [2]: A lock variable for internal use. */
#define NO_RACING 2
/*
* [1] is initialized to a large number, then decremented on every
* create/open, and incremented on every close. Makes it possible to
* use the "adjust" feature to account for processes which exit before
* calling sem_close().
*
* [2] is used to avoid the race conditions caused by sem_make()
* and sem_close(), as discussed in those functions.
*/
/* The maximum process count. */
#define BIGCOUNT 10000
/* Number of semaphores in the semaphore set. */
#define NSEMS 3
/******************************************************************************
* OPERATIONS
*
* System V's semop() will perform operations on arrays of
* type struct sembuf, combining the sequence of operations
* into atomic ones.
*
* In many of these operations, the flag SEM_UNDO is set, which
* causes the relevant operation to be undone in the event of
* the process abnormally terminating.
*
* struct sembuf {
* short sem_num Semaphore number
* short sem_op Semaphore operation
* short sem_flg Operation flags
* }
*
******************************************************************************/
/*
* LOCK
* 0. Wait for NO_RACING to be 0 (unlocked).
* 1. Increment NO_RACING to 1 (lock).
*/
#define nops_lock 2
static struct sembuf op_lock[nops_lock] = {
{NO_RACING, 0, 0},
{NO_RACING, 1, SEM_UNDO}
};
/*
* ENDCREATE
* 0. Decrement the PROCESSES counter.
* 1. Unlock NO_RACING (decrement to 0).
*/
#define nops_endcreate 2
static struct sembuf op_endcreate[nops_endcreate] = {
{PROCESSES, -1, SEM_UNDO},
{NO_RACING, -1, SEM_UNDO}
};
/*
* OPEN
* 0. Decrement PROCESSES.
*/
#define nops_open 1
static struct sembuf op_open[nops_open] = {
{PROCESSES, -1, SEM_UNDO}
};
/*
* CLOSE
* 0. Wait for NO_RACING to be 0 (unlocked).
* 1. Increment NO_RACING to 1 (lock).
* 2. Increment the PROCESSES counter.
*/
#define nops_close 3
static struct sembuf op_close[nops_close] = {
{NO_RACING, 0, 0},
{NO_RACING, 1, SEM_UNDO},
{PROCESSES, 1, SEM_UNDO}
};
/*
* UNLOCK
* Decrement NO_RACING to 0 (unlock).
*/
#define nops_unlock 1
static struct sembuf op_unlock[nops_unlock] = {
{NO_RACING, -1, SEM_UNDO}
};
/*
* SAFE SEMAPHORE OPERATION (WITH UNDO)
* 0. Decrement or increment SEMAPHORE by 99.
* NOTE
* The 99 is set to the actual amount to
* add or subtract (positive or negative).
*/
#define nops_sem 1
static struct sembuf op_sem[nops_sem] = {
{SEMAPHORE, 99, SEM_UNDO}
};
/*
* UNSAFE SEMAPHORE OPERATION (NO UNDO)
* 0. Decrement or increment SEMAPHORE by 99.
* NOTE
* The 99 is set to the actual amount to
* add or subtract (positive or negative).
*/
#define nops_raw 1
static struct sembuf op_raw[nops_raw] = {
{SEMAPHORE, 99, 0}
};
/******************************************************************************
* SEMAPHORE CONTROL UNION
*
* Filled in by semctl during certain calls, and while
* optional, should be provided each time. For more info
* about it, see man(3) semctl.
*
******************************************************************************/
union semun {
int val; /* Semaphore value */
struct semid_ds *buf; /* Semaphore status struct */
unsigned short *array; /* Used to set multiple semvals. */
} control;
/******************************************************************************
* UTILITY FUNCTIONS
******************************************************************************/
/**
* msem_operation
* ``````````````
* Wrap the System V semaphore function semop().
*
* @semid: Semaphore ID
* @sops : Semaphore operation array
* @nsops: Number of operations in @sops
* Return: -1 on error, else 0.
*
* NOTE
* This is intended to provide debugging assistance.
*/
int msem_operation(int semid, struct sembuf *sops, size_t nsops)
{
if (semop(semid, sops, nsops) == 0) {
return 0;
}
switch (errno) {
case E2BIG:
ERROR("[E2BIG] The value of nsops is greater than the system-imposed maximum\n");
break;
case EACCES:
ERROR("[EACCES] Permission is denied to the calling process\n");
break;
case EAGAIN:
ERROR("[EAGAIN] Would suspend calling process but &IPC_NOWAIT is non-zero\n");
break;
case EFBIG:
ERROR("[EFBIG] sem_num is less than 0 or >= #semaphores in this set\n");
break;
case EIDRM:
ERROR("[EIDRM] Semaphore ID %d has been removed from system\n", semid);
break;
case EINTR:
ERROR("[EINTR] Operation was interrupted by a signal\n");
break;
case EINVAL:
ERROR("[EINVAL] Not a valid semaphore ID, or SEM_UNDO exceeds system limit\n");
break;
case ENOSPC:
ERROR("[ENOSPC] Limit on processes requiring SEM_UNDO would be exceeded\n");
break;
case ERANGE:
ERROR("[ERANGE] Operation would cause a semval or semadj to overflow\n");
break;
}
return -1;
}
/**
* msem_key
* ````````
* Create a key token from a path and tag.
*
* @path : Path to the semaphore file.
* @tag : Project ID (must be non-zero).
* @create: Create file at @path if none exists.
* Return : Key suitable for semaphore use.
*/
int msem_key(char *path, int tag, bool create)
{
key_t key;
if (tag == 0) {
ERROR("Project tag must be non-zero.\n");
return -1;
}
if (access(path, F_OK) == -1) {
switch (create) {
case true:
if ((open(path, O_CREAT, 0666)) < 0) {
ERROR("(%d) Could not create file at %s\n", errno, path);
return -1;
} else {
DEBUG("Created new file at %s.\n", path);
}
break;
case false:
DEBUG("File at %s does not exist.\n", path);
return -1;
}
}
key = ftok(path, tag);
if (key == IPC_PRIVATE) {
DEBUG("Cannot create private semaphores.\n");
return -1;
} else if (key == (key_t)-1) {
DEBUG("Likely ftok() error.\n");
return -1;
}
return key;
}
/******************************************************************************
* ACCESSOR FUNCTIONS
*
* Retreive information about an operating semaphore.
* None of these functions require the caller to
* lock the semaphore being investigated.
*
******************************************************************************/
/**
* msem_value
* ``````````
* Current value of the semaphore
*
* @semid: Semaphore ID.
* Return: Value, -1 on error
*/
unsigned short msem_value(int semid)
{
register int semval;
control.val = 0;
if ((semval = semctl(semid, SEMAPHORE, GETVAL, control)) < 0) {
WARN("GETVAL failed.\n");
return -1;
}
return semval;
}
/**
* msem_pid
* ````````
* PID of the last process to modify the semaphore.
*
* @semid: Semaphore ID
* Return: PID value, -1 on error
*/
pid_t msem_pid(int semid)
{
register pid_t sempid;
control.val = 0;
if ((sempid = semctl(semid, SEMAPHORE, GETPID, control)) == -1) {
WARN("GETPID failed.\n");
return -1;
}
return sempid;
}
/**
* msem_ncount
* ```````````
* # of processes waiting for semaphore value to be greater than current value
*
* @semid: Semaphore ID
* Return: Process count, -1 on error
*/
unsigned short msem_ncount(int semid)
{
register unsigned short semncnt;
control.val = 0;
if ((semncnt = semctl(semid, SEMAPHORE, GETNCNT, control)) == -1) {
WARN("GETNCNT failed.\n");
return -1;
}
return semncnt;
}
/**
* msem_zcount
* ```````````
* # of processes waiting for semaphore value to be 0
*
* @semid: Semaphore ID.
* Return: Process count, -1 on error
*/
unsigned short msem_zcount(int semid)
{
register unsigned short semzcnt;
control.val = 0;
if ((semzcnt = semctl(semid, SEMAPHORE, GETZCNT, control)) == -1) {
WARN("GETZCNT failed.\n");
return -1;
}
return semzcnt;
}
/**
* msem_otime
* ``````````
* Time (sec. since UNIX epoch) of last semaphore operation
*
* @semid: Semaphore ID.
* Return: UNIX time, -1 on error
*/
int msem_otime(int semid)
{
int r;
if (control.buf == NULL) {
control.buf = calloc(1, sizeof(struct semid_ds));
}
if ((semctl(semid, SEMAPHORE, IPC_STAT, control)) == -1) {
WARN("IPC_STAT failed.\n");
return -1;
}
r = (int)control.buf->sem_otime;
if (control.buf != NULL) {
free(control.buf);
}
return r;
}
/**
* msem_ctime
* ``````````
* Time (sec. since UNIX epoch) of last semaphore control operation
*
* @semid: Semaphore ID.
* Return: UNIX time, -1 on error
*/
int msem_ctime(int semid)
{
int r;
if (control.buf == NULL) {
control.buf = calloc(1, sizeof(struct semid_ds));
}
if ((semctl(semid, SEMAPHORE, IPC_STAT, control)) < 0) {
WARN("IPC_STAT failed.\n");
return -1;
}
r = (int)control.buf->sem_ctime;
if (control.buf != NULL) {
free(control.buf);
}
return r;
}
int msem_query(int semid, char *query_code)
{
char code = query_code[0];
switch (code) {
case 'v':
return (int)msem_value(semid);
case 'p':
return (int)msem_pid(semid);
case 'n':
return (int)msem_ncount(semid);
case 'z':
return (int)msem_zcount(semid);
case 'o':
return (int)msem_otime(semid);
case 'c':
return (int)msem_ctime(semid);
default:
WARN("Invalid query_code\n");
return -1;
}
}
/******************************************************************************
* FILE RECORD AND STATE HANDLING
******************************************************************************/
struct msem_data {
struct {
char tag;
key_t key;
int semid;
} row[CHAR_MAX];
};
bool msem_scan(FILE *file, char *tag, key_t *key, int *semid)
{
static long pos=-1;
if (feof(file)) {
pos = -1;
return false;
}
if (pos!=-1) {
fseek(file, pos, SEEK_SET);
}
fscanf(file, "%c %d %d", tag, key, semid);
pos = ftell(file);
return true;
}
/**
* msem_record()
* `````````````
* Write the semaphore ID to the file associated with it.
*/
int msem_record(char *path, char tag, key_t key, int id)
{
FILE *file;
if ((file = fopen(path, "a+"))) {
fprintf(file, "%c %d %d\n", tag, key, id);
} else {
return -1;
}
fclose(file);
return 1;
}
/******************************************************************************
* LOW-LEVEL FUNCTIONS
*
* msem_create
* msem_remove
* msem_open
* msem_close
* msem_exists
*
******************************************************************************/
/**
* msem_create
* ```````````
* Create a semaphore with a specified initial value.
*
* @key : Key value (see sem_key)
* @init : Initial value of the semaphore.
* Return: Semaphore ID if all OK, else -1
*
* NOTE
* If the semaphore already exists, it isn't initialized.
*/
int msem_create(char *path, char *tags, int init)
{
key_t key;
register int id;
register char tag;
register int semval;
tag = tags[0];
/*
* Build the key used to get the semaphore ID from
* the kernel's shared memory space.
*/
if ((key = msem_key(path, tag, true)) == -1) {
ERROR("Could not fetch key for file %s[%c]\n", path, tag);
return -1;
}
again:
/*
* Try to create the semaphore. If it already exists,
* the IP_EXCL flag will ensure that semget() returns
* with an error.
*/
if ((id = semget(key, NSEMS, 0777|IPC_CREAT|IPC_EXCL)) < 0) {
//DEBUG("Semaphore exists, permission error, or tables full.\n");
return -1;
}
/*
* When the semaphore is created, we know that the value
* of all 3 members is 0.
*
* There is a race condition between the semget() above and
* the semop() below. Another process can call sem_close()
* and remove the semaphore (if that process is the last one
* using it).
*
* If the error condition occurs, we go back and create the
* semaphore anew.
*/
if ((msem_operation(id, &op_lock[0], nops_lock)) == -1) {
if (errno == EINVAL) {
DEBUG("Bullet caught with bare hands\n");
goto again;
} else {
ERROR("Can't lock the semaphore.\n");
return -1;
}
}
/*
* Get the value of the process counter. If it equals 0, then
* no one has initialized the semaphore yet.
*/
control.val = 0;
if ((semval = semctl(id, PROCESSES, GETVAL, control)) == -1) {
ERROR("Failed to get process count.\n");
return -1;
}
if (semval == 0) {
/*
* Instead of initializing it with SETALL, which would
* clear the adjust value set when we locked it above,
* we do 2 system calls to initialize [0] and [1].
*/
control.val = init;
if (semctl(id, SEMAPHORE, SETVAL, control) == -1) {
ERROR("Failed to set initial value.\n");
return -1;
}
control.val = BIGCOUNT;
if (semctl(id, PROCESSES, SETVAL, control) == -1) {
ERROR("Failed to initialize process count.\n");
return -1;
}
}
/*
* Decrement the process counter and then release the lock.
*/
if (msem_operation(id, &op_endcreate[0], nops_endcreate) == -1) {
ERROR("Semaphore creation did not end cleanly.\n");
return -1;
}
return id;
}
/**
* msem_remove
* ```````````
* Remove a semaphore from shared memory.
*
* @id : Semaphore ID.
* Return: TRUE on success, else FALSE.
*/
int msem_remove(int semid)
{
/*
* Perform the remove operation.
*/
control.val = 0;
if (semctl(semid, SEMAPHORE, IPC_RMID, control) == -1) {
WARN("Failed to remove semaphore.\n");
return -1;
}
return 1;
}
/**
* msem_open
* `````````
* Convert a semaphore (path,uid) tuple to a semaphore id.
*
* @path : Filesystem path to the semaphore.
* @tag : Tag (character) indicating the region of the file at @path.
* @init : Initial value to set the semaphore if it is created.
* Return: Semaphore id value on success, -1 on error (ENOENT usually)
*/
int msem_open(char *path, char *tags, int init)
{
register int s;
register char tag;
key_t key;
tag = (char)*tags;
/*
* Try to create the semaphore. If the semaphore
* already exists, sem_create will return error.
*
* If the error isn't EEXIST, its an actual problem
* and we have to quit.
*/
if ((s = msem_create(path, tags, init)) == -1) {
if (errno != EEXIST) {
DEBUG("Create error\n");
return -1;
} else {
DEBUG("Semaphore already exists\n");
/*
* The semaphore already exists. Build the key used
* to get the semaphore ID from the kernel's shared
* memory space.
*/
if ((key = msem_key(path, tag, true)) == -1) {
ERROR("Could not fetch key for file %s[%c]\n", path, tag);
return -1;
}
/*
* Get the semaphore ID of the existing semaphore.
* If the call to sem_create failed with EEXIST,
* this will set the value of 's'.
*/
if ((s = semget(key, NSEMS, 0)) == -1) {
ERROR("Still could not open semaphore\n");
return -1;
}
}
} else {
DEBUG("Created new semaphore %s[%c] with value %d\n", path, tag, init);
msem_record(path, tag, key, s);
}
/*
* Perform the open operation to provide the semaphore
* to your process.
*/
if (msem_operation(s, &op_open[0], nops_open) == -1) {
ERROR("Semaphore operation failed\n");
return -1;
}
return s;
}
/**
* msem_close
* ``````````
* Close a semaphore (used by exiting process).
*
* @semid: Semaphore ID.
* Return: TRUE on success, else FALSE.
*/
int msem_close(int semid)
{
register int semval;
/*
* Get a lock on the semaphore, then increment [1],
* the process counter.
*/
if (msem_operation(semid, &op_close[0], nops_close) == -1) {
ERROR("Failed to close semaphore.\n");
return -1;
}
/*
* Read the value of the process counter to see if this
* is the last reference to the semaphore.
*
* Causes the race condition discussed in sem_make().
*/
control.val = 0;
if ((semval = semctl(semid, PROCESSES, GETVAL, control)) == -1) {
ERROR("Failed to get process count.\n");
return -1;
}
if (semval > BIGCOUNT) {
ERROR("Process count (somehow) exceeds minimum.\n");
return -1;
} else if (semval == BIGCOUNT) {
WARN("Last process using semaphore. Removing semaphore.\n");
msem_remove(semid);
return 0;
} else {
if (msem_operation(semid, &op_unlock[0], nops_unlock) == -1) {
ERROR("Failed to unlock semaphore.\n");
return -1;
}
}
/* Decremented successfully */
return semval;
}
/**
* msem_exists()
* `````````````
* @path : Filesystem path to the semaphore.
* @tag : Tag (character) indicating the region of the file at @path.
* Return: TRUE if semaphore exists at @path:@tag, else FALSE
*/
int msem_exists(char *path, char *tags)
{
key_t key;
int id;
char tag;
tag = (char)*tags;
if ((key = ftok(path, tag)) == -1) {
return false;
}
if ((id = semget(key, 0, 0777)) == -1) {
return false;
}
if (shell("ipcs -s | awk '{print $2}' | grep -q %d", id)) {
return false;
}
return true;
}
/******************************************************************************
* TIMEOUT SUPPORT
******************************************************************************/
/*
* Set by the SIGALRM handler. Allows the caller
* to distinguish a timeout from some other error
* in the semaphore.
*/
volatile bool CAUGHT_ALARM = false;
/**
* sem_alarm_handler
* `````````````````
* Handler for SIGALRM signal.
*
* @signo: Signal number (should be SIGALRM).
* Return: Nothing.
*/
void msem_alarm_handler(int sig)
{
CAUGHT_ALARM = 1;
}
/**
* sem_alarm_ms
* ````````````
* Set a delayed SIGALRM signal.
*
* @ms : Number of milliseconds to delay.
* Return: 1 on success, -1 on error.
*/
int set_alarm(int ms)
{
struct itimerval when = {{0},{0}};
signal(SIGALRM, &msem_alarm_handler);
when.it_interval.tv_sec = 0;
when.it_interval.tv_usec = 0;
when.it_value.tv_sec = ms / SEC_IN_MS;
when.it_value.tv_usec = MS_TO_US((ms%SEC_IN_MS));
/*DEBUG("tv_sec: %ld\ntv_nsec: %ld\n", when.tv_sec, when.tv_nsec);*/
if ((setitimer(ITIMER_REAL, &when, 0)) == EINVAL) {
ERROR("Timer value not canonicalized.\n");
return -1;
}
DEBUG("Programmed thread death in %dms.\n", ms);
return 1;
}
/******************************************************************************
* SEMAPHORE OPERATIONS
******************************************************************************/
/**
* msem_set_once
* `````````````
* Alter a semaphore's value by some amount.
*
* @semid: Semaphore ID
* @value: Value to move semaphore.
* @ms : Milliseconds before timeout.
* Return: -1 on error, return value of semop on success.
*
* NOTE
* If the value of @ms is <= 0, no timeout will be
* set.
*/
int msem_set_once(int semid, int value, int ms)
{
pid_t pid = 1;
/*
* No operation is defined for value 0, so
* we have to prevent this being argued.
*/
if ((op_raw[0].sem_op = value) == 0) {
WARN("Semaphore operation value 0 not permitted.\n");
return -1;
}
/*
* If there are a valid number of milliseconds
* to wait, set the alarm handler before beginning
* the operation.
*/
if (ms > 0) {
if ((set_alarm(ms)) == -1) {
ERROR("Could not establish timer, aborting.\n");
return -1;
}
}
/*
* If the operation returns with an error, and the
* CAUGHT_ALARM global variable was set, the operation
* timed out.
*/
if ((msem_operation(semid, &op_raw[0], nops_raw)) == -1) {
if (CAUGHT_ALARM == true) {
DEBUG("Caught SIGALRM (timed out).\n");
pid = (int)getpid();
DEBUG("[%d] Programmed thread death.\n", pid);
CAUGHT_ALARM = false;
return -1;
} else {
WARN("Semaphore operation failed.\n");
return -1;
}
}
return pid;
}
/**
* msem_set_safe
* `````````````
* Alter a semaphore's value by some amount.
*
* @semid: Semaphore ID
* @value: Value to move semaphore.
* Return: -1 on error, return value of semop on success.
*
* NOTE
* If the value of @ms is <= 0, no timeout will be
* set.
*
* If the process dies while holding a semaphore, it will
* undo any semaphore tokens it decremented.
*/
int msem_set_safe(int semid, int value, int ms)
{
pid_t pid = 1;
/*
* No operation is defined for value 0, so
* we have to prevent this being argued.
*/
if ((op_sem[0].sem_op = value) == 0) {
WARN("Semaphore operation value 0 not permitted.\n");
return -1;
}
/*
* If there are a valid number of milliseconds
* to wait, set the alarm handler before beginning
* the operation.
*/
if (ms > 0) {
if ((set_alarm(ms)) == -1) {
ERROR("Could not establish timer, aborting.\n");
return -1;
}
}
/*
* If the operation returns with an error, and the
* CAUGHT_ALARM global variable was set, the operation
* timed out.
*/
if ((msem_operation(semid, &op_sem[0], nops_sem)) == -1) {
if (CAUGHT_ALARM == true) {
msem_close(semid);
DEBUG("Caught SIGALRM (timed out).\n");
pid = (int)getpid();
DEBUG("[%d] Programmed thread death.\n", pid);
CAUGHT_ALARM = false;
return -1;
} else {
WARN("Semaphore operation failed.\n");