1 #include <Python.h>
2 #include <semaphore.h>
3
4
5 static int
parse_sem_t(PyObject * object,void * address)6 parse_sem_t(PyObject *object, void *address)
7 {
8 *((sem_t **)address) = PyLong_AsVoidPtr(object);
9 return 1;
10 }
11
12
13 static PyObject *
namedsem_sem_open(PyObject * self,PyObject * args)14 namedsem_sem_open(PyObject *self, PyObject *args)
15 {
16 const char *name;
17 int oflag;
18 unsigned int value;
19 sem_t *result;
20
21 PyArg_ParseTuple(args, "siI", &name, &oflag, &value);
22 result = sem_open(name, oflag, 0600, value);
23
24 return PyLong_FromVoidPtr(result);
25 }
26
27 static PyObject *
namedsem_sem_close(PyObject * self,PyObject * args)28 namedsem_sem_close(PyObject *self, PyObject *args)
29 {
30 sem_t *sem;
31 int result;
32
33 PyArg_ParseTuple(args, "O&", &parse_sem_t, &sem);
34 result = sem_close(sem);
35
36 return Py_BuildValue("i", result);
37 }
38
39 static PyObject *
namedsem_sem_unlink(PyObject * self,PyObject * args)40 namedsem_sem_unlink(PyObject *self, PyObject *args)
41 {
42 const char *name;
43 int result;
44
45 PyArg_ParseTuple(args, "s", &name);
46 result = sem_unlink(name);
47
48 return Py_BuildValue("i", result);
49 }
50
51 static PyObject *
namedsem_sem_wait(PyObject * self,PyObject * args)52 namedsem_sem_wait(PyObject *self, PyObject *args)
53 {
54 sem_t *sem;
55 int result;
56
57 PyArg_ParseTuple(args, "O&", &parse_sem_t, &sem);
58 result = sem_wait(sem);
59
60 return Py_BuildValue("i", result);
61 }
62
63 static PyObject *
namedsem_sem_post(PyObject * self,PyObject * args)64 namedsem_sem_post(PyObject *self, PyObject *args)
65 {
66 sem_t *sem;
67 int result;
68
69 PyArg_ParseTuple(args, "O&", &parse_sem_t, &sem);
70 result = sem_post(sem);
71
72 return Py_BuildValue("i", result);
73 }
74
75
76 static PyObject *
namedsem_sem_getvalue(PyObject * self,PyObject * args)77 namedsem_sem_getvalue(PyObject *self, PyObject *args)
78 {
79 sem_t *sem;
80 int sval;
81
82 PyArg_ParseTuple(args, "O&", &parse_sem_t, &sem);
83 sem_getvalue(sem, &sval);
84
85 return Py_BuildValue("i", sval);
86 }
87
88
89
90 static PyMethodDef NamedsemMethods[] = {
91 {"sem_open", namedsem_sem_open, METH_VARARGS, "Execute sem_open()."},
92 {"sem_close", namedsem_sem_close, METH_VARARGS, "Execute sem_close()."},
93 {"sem_unlink", namedsem_sem_unlink, METH_VARARGS, "Execute sem_unlink()."},
94 {"sem_wait", namedsem_sem_wait, METH_VARARGS, "Execute sem_wait()."},
95 {"sem_post", namedsem_sem_post, METH_VARARGS, "Execute sem_post()."},
96 {"sem_getvalue", namedsem_sem_getvalue, METH_VARARGS, "Execute sem_getvalue()."},
97 {NULL, NULL, 0, NULL}
98 };
99
100 PyMODINIT_FUNC
initnamedsem(void)101 initnamedsem(void) {
102 PyObject *module;
103
104 module = Py_InitModule("namedsem", NamedsemMethods);
105 PyModule_AddIntConstant(module, "SEM_FAILED", (long)SEM_FAILED);
106 }
107