-
Notifications
You must be signed in to change notification settings - Fork 5
/
posix_ipc_module.c
2632 lines (2157 loc) · 79.2 KB
/
posix_ipc_module.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
/*
posix_ipc - A Python module for accessing POSIX 1003.1b-1993 semaphores,
shared memory and message queues.
Copyright (c) 2012, Philip Semanchuk
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 posix_ipc 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 ITS 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 Philip Semanchuk 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.
*/
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "structmember.h"
#include <time.h>
#include <sys/time.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
// Just for the math surrounding timeouts for sem_timedwait()
#include <math.h>
// For mq_notify
#include <signal.h>
#include <pthread.h>
#include "probe_results.h"
// For semaphore stuff
#include <semaphore.h>
// For shared memory stuff
#include <sys/stat.h>
#include <sys/mman.h>
#ifdef MESSAGE_QUEUE_SUPPORT_EXISTS
// For msg queues
#include <mqueue.h>
#endif
// define Py_TYPE for versions before Python 2.6
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
// define PyVarObject_HEAD_INIT for versions before Python 2.6
#ifndef PyVarObject_HEAD_INIT
#define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
#endif
/* SEM_FAILED is defined as an int in Apple's headers, and this makes the
compiler complain when I compare it to a pointer. Python faced the same
problem (issue 9586) and I copied their solution here.
ref: http://bugs.python.org/issue9586
Note that in /Developer/SDKs/MacOSX10.4u.sdk/usr/include/sys/semaphore.h,
SEM_FAILED is #defined as -1 and that's apparently the definition used by
Python when building. In /usr/include/sys/semaphore.h, it's defined
as ((sem_t *)-1).
*/
#ifdef __APPLE__
#undef SEM_FAILED
#define SEM_FAILED ((sem_t *)-1)
#endif
/* POSIX says that a mode_t "shall be an integer type". To avoid the need
for a specific get_mode function for each type, I'll just stuff the mode into
a long and mention it in the Xxx_members list for each type.
ref: http://www.opengroup.org/onlinepubs/000095399/basedefs/sys/types.h.html
*/
typedef struct {
PyObject_HEAD
char *name;
long mode;
sem_t *pSemaphore;
} Semaphore;
typedef struct {
PyObject_HEAD
char *name;
long mode;
int fd;
} SharedMemory;
#ifdef MESSAGE_QUEUE_SUPPORT_EXISTS
typedef struct {
PyObject_HEAD
char *name;
mqd_t mqd;
long mode;
long max_messages;
long max_message_size;
int send_permitted;
int receive_permitted;
PyObject *notification_callback;
PyObject *notification_callback_param;
// In the event that the user requests notifications in a new thread,
// I'll need a reference to the interpreter in order to create the
// thread for the callback. See request_notification() and
// process_notification() for details.
PyInterpreterState *interpreter;
} MessageQueue;
#endif
// FreeBSD (and perhaps other BSDs) limit names to 14 characters. In the
// code below, strings of this length are allocated on the stack, so
// increase this gently or change that code to use malloc().
#define MAX_SAFE_NAME_LENGTH 14
/* Struct to contain a timeout which can be None */
typedef struct {
int is_none;
int is_zero;
struct timespec timestamp;
} NoneableTimeout;
/* Struct to contain an IPC object name which can be None */
typedef struct {
int is_none;
char *name;
} NoneableName;
/*
Exceptions for this module
*/
static PyObject *pBaseException;
static PyObject *pPermissionsException;
static PyObject *pSignalException;
static PyObject *pExistentialException;
static PyObject *pBusyException;
#define ONE_BILLION 1000000000
#ifdef POSIX_IPC_DEBUG
#define DPRINTF(fmt, args...) fprintf(stderr, "+++ " fmt, ## args)
#else
#define DPRINTF(fmt, args...)
#endif
#if PY_MAJOR_VERSION > 2
static char *
bytes_to_c_string(PyObject* o, int lock) {
/* Convert a bytes object to a char *. Optionally lock the buffer if it is a
bytes array.
This code swiped directly from Python 3.1's posixmodule.c by Yours Truly.
The name there is bytes2str().
*/
if (PyBytes_Check(o))
return PyBytes_AsString(o);
else if (PyByteArray_Check(o)) {
if (lock && PyObject_GetBuffer(o, NULL, 0) < 0)
/* On a bytearray, this should not fail. */
PyErr_BadInternalCall();
return PyByteArray_AsString(o);
} else {
/* The FS converter should have verified that this
is either bytes or bytearray. */
Py_FatalError("bad object passed to bytes2str");
/* not reached. */
return "";
}
}
static void
release_bytes(PyObject* o)
/* Release the lock, decref the object.
This code swiped directly from Python 3.1's posixmodule.c by Yours Truly.
*/
{
if (PyByteArray_Check(o))
o->ob_type->tp_as_buffer->bf_releasebuffer(NULL, 0);
Py_DECREF(o);
}
#endif
static int
random_in_range(int min, int max) {
// returns a random int N such that min <= N <= max
int diff = (max - min) + 1;
// ref: http://www.c-faq.com/lib/randrange.html
return ((int)((double)rand() / ((double)RAND_MAX + 1) * diff)) + min;
}
static
int create_random_name(char *name) {
// The random name is always lowercase so that this code will work
// on case-insensitive file systems. It always starts with a forward
// slash.
int length;
char *alphabet = "abcdefghijklmnopqrstuvwxyz";
int i;
// Generate a random length for the name. I subtract 1 from the
// MAX_SAFE_NAME_LENGTH in order to allow for the name's leading "/".
length = random_in_range(6, MAX_SAFE_NAME_LENGTH - 1);
name[0] = '/';
name[length] = '\0';
i = length;
while (--i)
name[i] = alphabet[random_in_range(0, 25)];
return length;
}
static int
convert_name_param(PyObject *py_name_param, void *checked_name) {
/* Verifies that the py_name_param is either None or a string.
If it's a string, checked_name->name points to a PyMalloc-ed buffer
holding a NULL-terminated C version of the string when this function
concludes. The caller is responsible for releasing the buffer.
*/
int rc = 0;
NoneableName *p_name = (NoneableName *)checked_name;
#if PY_MAJOR_VERSION > 2
PyObject *py_name_as_bytes = NULL;
char *p_name_as_c_string = NULL;
#endif
DPRINTF("inside convert_name_param\n");
DPRINTF("PyBytes_Check() = %d \n", PyBytes_Check(py_name_param));
DPRINTF("PyString_Check() = %d \n", PyString_Check(py_name_param));
DPRINTF("PyUnicode_Check() = %d \n", PyUnicode_Check(py_name_param));
p_name->is_none = 0;
// The name can be None or a Python string
if (py_name_param == Py_None) {
DPRINTF("name is None\n");
rc = 1;
p_name->is_none = 1;
}
#if PY_MAJOR_VERSION > 2
else if (PyUnicode_Check(py_name_param) || PyBytes_Check(py_name_param)) {
DPRINTF("name is Unicode or bytes\n");
// The caller passed me a Unicode string or a byte array; I need a
// char *. Getting from one to the other takes a couple steps.
if (PyUnicode_Check(py_name_param)) {
DPRINTF("name is Unicode\n");
// PyUnicode_FSConverter() converts the Unicode object into a
// bytes or a bytearray object. (Why can't it be one or the other?)
PyUnicode_FSConverter(py_name_param, &py_name_as_bytes);
}
else {
DPRINTF("name is bytes\n");
// Make a copy of the name param.
py_name_as_bytes = PyBytes_FromObject(py_name_param);
}
// bytes_to_c_string() returns a pointer to the buffer.
p_name_as_c_string = bytes_to_c_string(py_name_as_bytes, 0);
// PyMalloc memory and copy the user-supplied name to it.
p_name->name = (char *)PyMem_Malloc(strlen(p_name_as_c_string) + 1);
if (p_name->name) {
rc = 1;
strcpy(p_name->name, p_name_as_c_string);
}
else
PyErr_SetString(PyExc_MemoryError, "Out of memory");
// The bytes version of the name isn't useful to me, and per the
// documentation for PyUnicode_FSConverter(), I am responsible for
// releasing it when I'm done.
release_bytes(py_name_as_bytes);
}
#else
else if (PyString_Check(py_name_param) || PyUnicode_Check(py_name_param)) {
DPRINTF("name is string or unicode\n");
// PyMalloc memory and copy the user-supplied name to it.
p_name->name = (char *)PyMem_Malloc(PyString_Size(py_name_param) + 1);
if (p_name->name) {
rc = 1;
strcpy(p_name->name, PyString_AsString(py_name_param));
}
else
PyErr_SetString(PyExc_MemoryError, "Out of memory");
}
#endif
else
PyErr_SetString(PyExc_TypeError, "Name must be None or a string");
return rc;
}
static
int convert_timeout(PyObject *py_timeout, void *converted_timeout) {
// Converts a PyObject into a timeout if possible. The PyObject should
// be None or some sort of numeric value (e.g. int, float, etc.)
// converted_timeout should point to a NoneableTimeout. When this function
// returns, if the NoneableTimeout's is_none is true, then the rest of the
// struct is undefined. Otherwise, the rest of the struct is populated.
int rc = 0;
double simple_timeout = 0;
struct timeval current_time;
NoneableTimeout *p_timeout = (NoneableTimeout *)converted_timeout;
// The timeout can be None or any Python numeric type (float,
// int, long).
if (py_timeout == Py_None)
rc = 1;
else if (PyFloat_Check(py_timeout)) {
rc = 1;
simple_timeout = PyFloat_AsDouble(py_timeout);
}
#if PY_MAJOR_VERSION < 3
else if (PyInt_Check(py_timeout)) {
rc = 1;
simple_timeout = (double)PyInt_AsLong(py_timeout);
}
#endif
else if (PyLong_Check(py_timeout)) {
rc = 1;
simple_timeout = (double)PyLong_AsLong(py_timeout);
}
// The timeout may not be negative.
if ((rc) && (simple_timeout < 0))
rc = 0;
if (!rc)
PyErr_SetString(PyExc_TypeError,
"The timeout must be None or a non-negative number");
else {
if (py_timeout == Py_None)
p_timeout->is_none = 1;
else {
p_timeout->is_none = 0;
p_timeout->is_zero = (!simple_timeout);
gettimeofday(¤t_time, NULL);
simple_timeout += current_time.tv_sec;
simple_timeout += (float)current_time.tv_usec / 1e6;
p_timeout->timestamp.tv_sec = (time_t)floor(simple_timeout);
p_timeout->timestamp.tv_nsec = (long)((simple_timeout - floor(simple_timeout)) * ONE_BILLION);
}
}
return rc;
}
static PyObject *
generic_str(char *name) {
#if PY_MAJOR_VERSION > 2
return PyUnicode_FromString(name ? name : "(no name)");
#else
return PyString_FromString(name ? name : "(no name)");
#endif
}
static void
mode_to_str(long mode, char *mode_str) {
// Given a numeric mode and preallocated string space, populates the
// string with the mode formatted as an octal number.
sprintf(mode_str, "0%o", (int)mode);
}
static int test_semaphore_validity(Semaphore *p) {
// Returns 1 (true) if the Semaphore object refers to a valid
// semaphore, 0 (false) otherwise. In the latter case, it sets the
// Python exception info and the caller should immediately return NULL.
// The false condition should not arise unless the user of the module
// tries to use a Semaphore after it's been closed.
int valid = 1;
if (!p->pSemaphore) {
valid = 0;
PyErr_SetString(pExistentialException, "The semaphore has been closed");
}
return valid;
}
/* ===== Semaphore implementation functions ===== */
static PyObject *
sem_str(Semaphore *self) {
return generic_str(self->name);
}
static PyObject *
sem_repr(Semaphore *self) {
char mode[32];
mode_to_str(self->mode, mode);
#if PY_MAJOR_VERSION > 2
return PyUnicode_FromFormat("posix_ipc.Semaphore(\"%s\", mode=%s)",
self->name, mode);
#else
return PyString_FromFormat("posix_ipc.Semaphore(\"%s\", mode=%s)",
self->name, mode);
#endif
}
static PyObject *
my_sem_unlink(const char *name) {
DPRINTF("unlinking sem name %s\n", name);
if (-1 == sem_unlink(name)) {
switch (errno) {
case EACCES:
PyErr_SetString(pPermissionsException,
"Denied permission to unlink this semaphore");
break;
case ENOENT:
case EINVAL:
PyErr_SetString(pExistentialException,
"No semaphore exists with the specified name");
break;
case ENAMETOOLONG:
PyErr_SetString(PyExc_ValueError, "The name is too long");
break;
default:
PyErr_SetFromErrno(PyExc_OSError);
break;
}
goto error_return;
}
Py_RETURN_NONE;
error_return:
return NULL;
}
static void
Semaphore_dealloc(Semaphore *self) {
/* Note -- I make no attempt to close the semaphore because that
kills access to the semaphore for every thread in this process,
which would make multi-threaded programming difficult.
*/
DPRINTF("dealloc\n");
PyMem_Free(self->name);
self->name = NULL;
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject *
Semaphore_new(PyTypeObject *type, PyObject *args, PyObject *kwlist) {
Semaphore *self;
self = (Semaphore *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
static int
Semaphore_init(Semaphore *self, PyObject *args, PyObject *keywords) {
NoneableName name;
char temp_name[MAX_SAFE_NAME_LENGTH + 1];
unsigned int initial_value = 0;
int flags = 0;
static char *keyword_list[ ] = {"name", "flags", "mode", "initial_value", NULL};
// First things first -- initialize the self struct.
self->pSemaphore = NULL;
self->name = NULL;
self->mode = 0600;
// Semaphore(name, [flags = 0, [mode = 0600, [initial_value = 0]]])
if (!PyArg_ParseTupleAndKeywords(args, keywords, "O&|iiI", keyword_list,
&convert_name_param, &name, &flags,
&(self->mode), &initial_value))
goto error_return;
if ( !(flags & O_CREAT) && (flags & O_EXCL) ) {
PyErr_SetString(PyExc_ValueError,
"O_EXCL must be combined with O_CREAT");
goto error_return;
}
if (name.is_none && ((flags & O_EXCL) != O_EXCL)) {
PyErr_SetString(PyExc_ValueError,
"Name can only be None if O_EXCL is set");
goto error_return;
}
if (name.is_none) {
// (name == None) ==> generate a name for the caller
do {
errno = 0;
create_random_name(temp_name);
DPRINTF("Calling sem_open, name=%s, flags=0x%x, mode=0%o, initial value=%d\n",
temp_name, flags, (int)self->mode, initial_value);
self->pSemaphore = sem_open(temp_name, flags, (mode_t)self->mode,
initial_value);
} while ( (SEM_FAILED == self->pSemaphore) && (EEXIST == errno) );
// PyMalloc memory and copy the randomly-generated name to it.
self->name = (char *)PyMem_Malloc(strlen(temp_name) + 1);
if (self->name)
strcpy(self->name, temp_name);
else {
PyErr_SetString(PyExc_MemoryError, "Out of memory");
goto error_return;
}
}
else {
// (name != None) ==> use name supplied by the caller. It was
// already converted to C by convert_name_param().
self->name = name.name;
DPRINTF("Calling sem_open, name=%s, flags=0x%x, mode=0%o, initial value=%d\n",
self->name, flags, (int)self->mode, initial_value);
self->pSemaphore = sem_open(self->name, flags, (mode_t)self->mode,
initial_value);
}
DPRINTF("pSemaphore == %p\n", self->pSemaphore);
if (self->pSemaphore == SEM_FAILED) {
self->pSemaphore = NULL;
switch (errno) {
case EACCES:
PyErr_SetString(pPermissionsException,
"Permission denied");
break;
case EEXIST:
PyErr_SetString(pExistentialException,
"A semaphore with the specified name already exists");
break;
case ENOENT:
PyErr_SetString(pExistentialException,
"No semaphore exists with the specified name");
break;
case EINVAL:
PyErr_SetString(PyExc_ValueError, "Invalid parameter(s)");
break;
case EMFILE:
PyErr_SetString(PyExc_OSError,
"This process already has the maximum number of files open");
break;
case ENFILE:
PyErr_SetString(PyExc_OSError,
"The system limit on the total number of open files has been reached");
break;
case ENAMETOOLONG:
PyErr_SetString(PyExc_ValueError, "The name is too long");
break;
case ENOMEM:
PyErr_SetString(PyExc_MemoryError, "Not enough memory");
break;
default:
PyErr_SetFromErrno(PyExc_OSError);
break;
}
goto error_return;
}
// else
// all is well, nothing to do
return 0;
error_return:
return -1;
}
static PyObject *
Semaphore_release(Semaphore *self) {
if (!test_semaphore_validity(self))
goto error_return;
if (-1 == sem_post(self->pSemaphore)) {
switch (errno) {
case EINVAL:
case EBADF:
PyErr_SetString(pExistentialException,
"The semaphore does not exist");
break;
default:
PyErr_SetFromErrno(PyExc_OSError);
break;
}
goto error_return;
}
Py_RETURN_NONE;
error_return:
return NULL;
}
static PyObject *
Semaphore_acquire(Semaphore *self, PyObject *args, PyObject *keywords) {
NoneableTimeout timeout;
int rc = 0;
if (!test_semaphore_validity(self))
goto error_return;
// Initialize this to the default of None.
timeout.is_none = 1;
// acquire([timeout=None])
if (!PyArg_ParseTuple(args, "|O&", convert_timeout, &timeout))
goto error_return;
Py_BEGIN_ALLOW_THREADS
// timeout == None: no timeout, i.e. wait forever.
// timeout == 0: raise an error if a wait would occur.
// timeout > 0: wait no longer than t seconds before raising an error.
if (timeout.is_none) {
DPRINTF("calling sem_wait()\n");
rc = sem_wait(self->pSemaphore);
}
else {
// Timeout is not None (i.e. is numeric)
// A simple_timeout of zero implies the same behavior as
// sem_trywait() so I call that instead. Doing so makes it easier
// to ensure this code behaves consistently regardless of whether
// or not sem_timedwait() is available.
if (timeout.is_zero) {
DPRINTF("calling sem_trywait()\n");
rc = sem_trywait(self->pSemaphore);
}
else {
// timeout is not None and is > 0.0
// sem_timedwait isn't available on all systems. Where it's not
// available I call sem_wait() instead.
#ifdef SEM_TIMEDWAIT_EXISTS
DPRINTF("calling sem_timedwait()\n");
DPRINTF("timeout tv_sec = %ld; timeout tv_nsec = %ld\n",
timeout.timestamp.tv_sec, timeout.timestamp.tv_nsec);
rc = sem_timedwait(self->pSemaphore, &(timeout.timestamp));
#else
DPRINTF("calling sem_wait()\n");
rc = sem_wait(self->pSemaphore);
#endif
}
}
Py_END_ALLOW_THREADS
if (-1 == rc) {
DPRINTF("sem_wait() rc = %d, errno = %d\n", rc, errno);
switch (errno) {
case EBADF:
case EINVAL:
// Linux documentation says that EINVAL has two meanings --
// 1) self->pSemaphore no longer points to a valid semaphore
// 2) timeout is < 0 or > one billion.
// Since my code above guards against out-of-range
// timeout values, I expect the second condition is
// impossible here.
PyErr_SetString(pExistentialException,
"The semaphore does not exist");
break;
case EINTR:
/* If the signal was generated by Ctrl-C, calling
PyErr_CheckSignals() here has the side effect of setting
Python's error indicator. Otherwise there's a good chance
it won't be set.
http://groups.google.com/group/comp.lang.python/browse_thread/thread/ada39e984dfc3da6/fd6becbdce91a6be?#fd6becbdce91a6be
*/
PyErr_CheckSignals();
if (!(PyErr_Occurred() &&
PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
) {
PyErr_Clear();
PyErr_SetString(pSignalException,
"The wait was interrupted by a signal");
}
// else
// If KeyboardInterrupt error is set, I propogate that
// up to the caller.
break;
case EAGAIN:
case ETIMEDOUT:
PyErr_SetString(pBusyException,
"Semaphore is busy");
break;
default:
PyErr_SetFromErrno(PyExc_OSError);
break;
}
goto error_return;
}
Py_RETURN_NONE;
error_return:
return NULL;
}
// sem_getvalue isn't available on all systems.
#ifdef SEM_GETVALUE_EXISTS
static PyObject *
Semaphore_getvalue(Semaphore *self, void *closure) {
int value;
if (!test_semaphore_validity(self))
goto error_return;
if (-1 == sem_getvalue(self->pSemaphore, &value)) {
switch (errno) {
case EINVAL:
PyErr_SetString(pExistentialException,
"The semaphore does not exist");
break;
default:
PyErr_SetFromErrno(PyExc_OSError);
break;
}
goto error_return;
}
return Py_BuildValue("i", value);
error_return:
return NULL;
}
// end #ifdef SEM_GETVALUE_EXISTS
#endif
static PyObject *
Semaphore_unlink(Semaphore *self) {
if (!test_semaphore_validity(self))
goto error_return;
return my_sem_unlink(self->name);
error_return:
return NULL;
}
static PyObject *
Semaphore_close(Semaphore *self) {
if (!test_semaphore_validity(self))
goto error_return;
if (-1 == sem_close(self->pSemaphore)) {
switch (errno) {
case EINVAL:
PyErr_SetString(pExistentialException,
"The semaphore does not exist");
break;
default:
PyErr_SetFromErrno(PyExc_OSError);
break;
}
goto error_return;
}
else
self->pSemaphore = NULL;
Py_RETURN_NONE;
error_return:
return NULL;
}
static PyObject *
Semaphore_enter(Semaphore *self) {
PyObject *args = PyTuple_New(0);
PyObject *retval = NULL;
if (Semaphore_acquire(self, args, NULL)) {
retval = (PyObject *)self;
Py_INCREF(self);
}
/* else acquisition failed for some reason so just fall through to
the return statement below and return NULL. Semaphore_acquire() has
already called PyErr_SetString() to set the relevant error.
*/
Py_DECREF(args);
return retval;
}
static PyObject *
Semaphore_exit(Semaphore *self, PyObject *args) {
DPRINTF("exiting context and releasing semaphore %s\n", self->name);
return Semaphore_release(self);
}
/* ===== End Semaphore functions ===== */
/* ===== Begin Shared Memory implementation functions ===== */
static PyObject *
shm_str(SharedMemory *self) {
return generic_str(self->name);
}
static PyObject *
shm_repr(SharedMemory *self) {
char mode[32];
mode_to_str(self->mode, mode);
#if PY_MAJOR_VERSION > 2
return PyUnicode_FromFormat("posix_ipc.SharedMemory(\"%s\", mode=%s)",
self->name, mode);
#else
return PyString_FromFormat("posix_ipc.SharedMemory(\"%s\", mode=%s)",
self->name, mode);
#endif
}
static PyObject *
my_shm_unlink(const char *name) {
DPRINTF("unlinking shm name %s\n", name);
if (-1 == shm_unlink(name)) {
switch (errno) {
case EACCES:
PyErr_SetString(pPermissionsException, "Permission denied");
break;
case ENOENT:
PyErr_SetString(pExistentialException,
"No shared memory exists with the specified name");
break;
case ENAMETOOLONG:
PyErr_SetString(PyExc_ValueError, "The name is too long");
break;
default:
PyErr_SetFromErrno(PyExc_OSError);
break;
}
goto error_return;
}
Py_RETURN_NONE;
error_return:
return NULL;
}
static PyObject *
SharedMemory_new(PyTypeObject *type, PyObject *args, PyObject *kwlist) {
SharedMemory *self;
self = (SharedMemory *)type->tp_alloc(type, 0);
return (PyObject *)self;
}
static int
SharedMemory_init(SharedMemory *self, PyObject *args, PyObject *keywords) {
NoneableName name;
char temp_name[MAX_SAFE_NAME_LENGTH + 1];
unsigned int flags = 0;
unsigned long size = 0;
int read_only = 0;
static char *keyword_list[ ] = {"name", "flags", "mode", "size", "read_only", NULL};
// First things first -- initialize the self struct.
self->name = NULL;
self->fd = 0;
self->mode = 0600;
if (!PyArg_ParseTupleAndKeywords(args, keywords, "O&|Iiki", keyword_list,
&convert_name_param, &name, &flags,
&(self->mode), &size, &read_only))
goto error_return;
if ( !(flags & O_CREAT) && (flags & O_EXCL) ) {
PyErr_SetString(PyExc_ValueError,
"O_EXCL must be combined with O_CREAT");
goto error_return;
}
if (name.is_none && ((flags & O_EXCL) != O_EXCL)) {
PyErr_SetString(PyExc_ValueError,
"Name can only be None if O_EXCL is set");
goto error_return;
}
flags |= (read_only ? O_RDONLY : O_RDWR);
if (name.is_none) {
// (name == None) ==> generate a name for the caller
do {
errno = 0;
create_random_name(temp_name);
DPRINTF("calling shm_open, name=%s, flags=0x%x, mode=0%o\n",
temp_name, flags, (int)self->mode);
self->fd = shm_open(temp_name, flags, (mode_t)self->mode);
} while ( (-1 == self->fd) && (EEXIST == errno) );
// PyMalloc memory and copy the randomly-generated name to it.
self->name = (char *)PyMem_Malloc(strlen(temp_name) + 1);
if (self->name)
strcpy(self->name, temp_name);
else {
PyErr_SetString(PyExc_MemoryError, "Out of memory");
goto error_return;
}
}
else {
// (name != None) ==> use name supplied by the caller. It was
// already converted to C by convert_name_param().
self->name = name.name;
DPRINTF("calling shm_open, name=%s, flags=0x%x, mode=0%o\n",
self->name, flags, (int)self->mode);
self->fd = shm_open(self->name, flags, (mode_t)self->mode);
}
DPRINTF("shm fd = %d\n", self->fd);
if (-1 == self->fd) {
self->fd = 0;
switch (errno) {
case EACCES:
PyErr_Format(pPermissionsException,
"No permission to %s this segment",
(flags & O_TRUNC) ? "truncate" : "access"
);