1 /***************************************************************************
2 * Copyright 1995, Technion, Israel Institute of Technology
3 * Electrical Eng, Software Lab.
4 * Author: Michael Veksler.
5 ***************************************************************************
7 * Purpose: Handle semaphores for shared memory operations.
8 ***************************************************************************
16 #include "debugtools.h"
17 #include "shm_semaph.h"
19 DEFAULT_DEBUG_CHANNEL(sem
)
23 /* IMPORTANT: Make sure that killed process will not lock everything.
24 * If possible, restrict usage of these functions.
26 void shm_read_wait(shm_sem semid
)
31 TRACE("(%d)\n",semid
);
32 sop
[0].sem_num
=SEM_READ
;
33 sop
[0].sem_op
=1; /* add this read instance */
34 sop
[0].sem_flg
=SEM_UNDO
; /* undo in case process dies */
36 sop
[1].sem_num
=SEM_WRITE
;
37 sop
[1].sem_op
=0; /* wait until no writing instance exists */
38 sop
[1].sem_flg
=SEM_UNDO
;
41 ret
=semop (semid
,sop
, 2);
42 } while (ret
<0 && errno
==EINTR
); /* interrupted system call? */
45 WARN("(semid=%d,errno=%d): Failed semaphore lock for read\n",
48 void shm_write_wait(shm_sem semid
)
53 TRACE("(%d)\n",semid
);
54 sop
[0].sem_num
=SEM_READ
;
55 sop
[0].sem_op
=0; /* wait until no reading instance exist */
56 sop
[0].sem_flg
=SEM_UNDO
;
58 sop
[1].sem_num
=SEM_WRITE
;
59 sop
[1].sem_op
=1; /* writing is in progress - disable read */
60 sop
[1].sem_flg
=SEM_UNDO
; /* undo if process dies */
62 sop
[2].sem_num
=SEM_READ
;
63 sop
[2].sem_op
=1; /* disable new writes */
64 sop
[2].sem_flg
=SEM_UNDO
;
67 ret
=semop (semid
,sop
, 3);
68 } while (ret
<0 && errno
==EINTR
); /* interrupted system call? */
70 if (ret
<0) /* test for the error */
71 WARN("(semid=%d,errno=%d): Failed semaphore lock for write\n",
74 void shm_write_signal(shm_sem semid
)
79 TRACE("(%d)\n",semid
);
80 sop
[0].sem_num
=SEM_READ
;
82 sop
[0].sem_flg
=IPC_NOWAIT
| SEM_UNDO
; /* no reason to wait */
84 sop
[1].sem_num
=SEM_WRITE
;
86 sop
[1].sem_flg
=IPC_NOWAIT
| SEM_UNDO
; /* no reason to wait */
89 ret
=semop (semid
,sop
, 2);
90 } while (ret
<0 && errno
==EINTR
); /* interrupted system call? */
92 if (ret
<0) /* test for the error */
93 WARN("(semid=%d,errno=%d): Failed semaphore unlock for write\n",
97 void shm_read_signal(shm_sem semid
)
102 TRACE("(%d)\n",semid
);
103 sop
[0].sem_num
=SEM_READ
;
105 sop
[0].sem_flg
=IPC_NOWAIT
| SEM_UNDO
; /* no reason to wait */
108 ret
=semop (semid
,sop
, 1);
109 } while (ret
<0 && errno
==EINTR
); /* interrupted system call? */
111 if (ret
<0) /* test for the error */
112 WARN("(semid=%d,errno=%d): Failed semaphore unlock for read\n",
116 void shm_sem_init(shm_sem
*sptr
)
121 semid
=semget (IPC_PRIVATE
, 2, 0700 | IPC_CREAT
);
124 semctl (semid
, 0, SETVAL
, arg
);
125 semctl (semid
, 1, SETVAL
, arg
);
129 void shm_sem_done(shm_sem
*semptr
)
133 semctl (*semptr
, 0, IPC_RMID
, arg
);
134 semctl (*semptr
, 1, IPC_RMID
, arg
);
139 #endif /* CONFIG_IPC */