2 .\" Copyright (C) 2006 Michael Kerrisk <mtk.manpages@gmail.com>
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date. The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein. The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
26 .TH SEM_WAIT 3 2014-02-26 "Linux" "Linux Programmer's Manual"
28 sem_wait, sem_timedwait, sem_trywait \- lock a semaphore
31 .B #include <semaphore.h>
33 .BI "int sem_wait(sem_t *" sem );
35 .BI "int sem_trywait(sem_t *" sem );
37 .BI "int sem_timedwait(sem_t *" sem ", const struct timespec *" abs_timeout );
40 Link with \fI\-pthread\fP.
43 Feature Test Macro Requirements for glibc (see
44 .BR feature_test_macros (7)):
48 _POSIX_C_SOURCE\ >=\ 200112L || _XOPEN_SOURCE\ >=\ 600
51 decrements (locks) the semaphore pointed to by
53 If the semaphore's value is greater than zero,
54 then the decrement proceeds, and the function returns, immediately.
55 If the semaphore currently has the value zero,
56 then the call blocks until either it becomes possible to perform
57 the decrement (i.e., the semaphore value rises above zero),
58 or a signal handler interrupts the call.
63 except that if the decrement cannot be immediately performed,
64 then call returns an error
75 specifies a limit on the amount of time that the call
76 should block if the decrement cannot be immediately performed.
79 argument points to a structure that specifies an absolute timeout
80 in seconds and nanoseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
81 This structure is defined as follows:
86 time_t tv_sec; /* Seconds */
87 long tv_nsec; /* Nanoseconds [0 .. 999999999] */
92 If the timeout has already expired by the time of the call,
93 and the semaphore could not be locked immediately,
96 fails with a timeout error
101 If the operation can be performed immediately, then
103 never fails with a timeout error, regardless of the value of
105 Furthermore, the validity of
107 is not checked in this case.
109 All of these functions return 0 on success;
110 on error, the value of the semaphore is left unchanged,
113 is set to indicate the error.
117 The call was interrupted by a signal handler; see
122 is not a valid semaphore.
124 The following additional error can occur for
128 The operation could not be performed without blocking (i.e., the
129 semaphore currently has the value zero).
131 The following additional errors can occur for
132 .BR sem_timedwait ():
136 .I abs_timeout.tv_nsecs
137 is less than 0, or greater than or equal to 1000 million.
140 The call timed out before the semaphore could be locked.
141 .\" POSIX.1-2001 also allows EDEADLK -- "A deadlock condition
142 .\" was detected", but this does not occur on Linux(?).
144 .SS Multithreading (see pthreads(7))
150 functions are thread-safe.
154 A signal handler always interrupts a blocked call to
155 one of these functions, regardless of the use of the
159 .\" sem_wait() is always interrupted on most other implementations,
160 .\" but on FreeBSD 5.4 SA_RESTART does cause restarting.
163 The (somewhat trivial) program shown below operates on an
165 The program expects two command-line arguments.
166 The first argument specifies a seconds value that is used to
167 set an alarm timer to generate a
170 This handler performs a
172 to increment the semaphore that is being waited on in
175 .BR sem_timedwait ().
176 The second command-line argument specifies the length
177 of the timeout, in seconds, for
178 .BR sem_timedwait ().
179 The following shows what happens on two different runs of the program:
183 .RB "$" " ./a.out 2 3"
184 About to call sem_timedwait()
185 sem_post() from handler
186 sem_timedwait() succeeded
187 .RB "$" " ./a.out 2 1"
188 About to call sem_timedwait()
189 sem_timedwait() timed out
198 #include <semaphore.h>
206 #define handle_error(msg) \\
207 do { perror(msg); exit(EXIT_FAILURE); } while (0)
212 write(STDOUT_FILENO, "sem_post() from handler\\n", 24);
213 if (sem_post(&sem) == \-1) {
214 write(STDERR_FILENO, "sem_post() failed\\n", 18);
220 main(int argc, char *argv[])
227 fprintf(stderr, "Usage: %s <alarm\-secs> <wait\-secs>\\n",
232 if (sem_init(&sem, 0, 0) == \-1)
233 handle_error("sem_init");
235 /* Establish SIGALRM handler; set alarm timer using argv[1] */
237 sa.sa_handler = handler;
238 sigemptyset(&sa.sa_mask);
240 if (sigaction(SIGALRM, &sa, NULL) == \-1)
241 handle_error("sigaction");
243 alarm(atoi(argv[1]));
245 /* Calculate relative interval as current time plus
246 number of seconds given argv[2] */
248 if (clock_gettime(CLOCK_REALTIME, &ts) == \-1)
249 handle_error("clock_gettime");
251 ts.tv_sec += atoi(argv[2]);
253 printf("main() about to call sem_timedwait()\\n");
254 while ((s = sem_timedwait(&sem, &ts)) == \-1 && errno == EINTR)
255 continue; /* Restart if interrupted by handler */
257 /* Check what happened */
260 if (errno == ETIMEDOUT)
261 printf("sem_timedwait() timed out\\n");
263 perror("sem_timedwait");
265 printf("sem_timedwait() succeeded\\n");
267 exit((s == 0) ? EXIT_SUCCESS : EXIT_FAILURE);
271 .BR clock_gettime (2),
272 .BR sem_getvalue (3),
274 .BR sem_overview (7),