malloc.3: ffix
[man-pages.git] / man3 / sem_wait.3
blobbc7988a1aff19b96bd2ed4e2f87af4f98a65b766
1 .\" Copyright (C) 2006 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\"
3 .\" %%%LICENSE_START(VERBATIM)
4 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
7 .\"
8 .\" Permission is granted to copy and distribute modified versions of this
9 .\" manual under the conditions for verbatim copying, provided that the
10 .\" entire resulting derived work is distributed under the terms of a
11 .\" permission notice identical to this one.
12 .\"
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
15 .\" responsibility for errors or omissions, or for damages resulting from
16 .\" the use of the information contained herein.  The author(s) may not
17 .\" have taken the same level of care in the production of this manual,
18 .\" which is licensed free of charge, as they might when working
19 .\" professionally.
20 .\"
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
23 .\" %%%LICENSE_END
24 .\"
25 .TH SEM_WAIT 3 2021-08-27 "Linux" "Linux Programmer's Manual"
26 .SH NAME
27 sem_wait, sem_timedwait, sem_trywait \- lock a semaphore
28 .SH SYNOPSIS
29 .nf
30 .B #include <semaphore.h>
31 .PP
32 .BI "int sem_wait(sem_t *" sem );
33 .BI "int sem_trywait(sem_t *" sem );
34 .BI "int sem_timedwait(sem_t *restrict " sem ,
35 .BI "                  const struct timespec *restrict " abs_timeout );
36 .fi
37 .PP
38 Link with \fI\-pthread\fP.
39 .PP
40 .RS -4
41 Feature Test Macro Requirements for glibc (see
42 .BR feature_test_macros (7)):
43 .RE
44 .PP
45 .BR sem_timedwait ():
46 .nf
47     _POSIX_C_SOURCE >= 200112L
48 .fi
49 .SH DESCRIPTION
50 .BR sem_wait ()
51 decrements (locks) the semaphore pointed to by
52 .IR sem .
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.
59 .PP
60 .BR sem_trywait ()
61 is the same as
62 .BR sem_wait (),
63 except that if the decrement cannot be immediately performed,
64 then call returns an error
65 .RI ( errno
66 set to
67 .BR EAGAIN )
68 instead of blocking.
69 .PP
70 .BR sem_timedwait ()
71 is the same as
72 .BR sem_wait (),
73 except that
74 .I abs_timeout
75 specifies a limit on the amount of time that the call
76 should block if the decrement cannot be immediately performed.
77 The
78 .I abs_timeout
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:
82 .PP
83 .in +4n
84 .EX
85 struct timespec {
86     time_t tv_sec;      /* Seconds */
87     long   tv_nsec;     /* Nanoseconds [0 .. 999999999] */
89 .EE
90 .in
91 .PP
92 If the timeout has already expired by the time of the call,
93 and the semaphore could not be locked immediately,
94 then
95 .BR sem_timedwait ()
96 fails with a timeout error
97 .RI ( errno
98 set to
99 .BR ETIMEDOUT ).
101 If the operation can be performed immediately, then
102 .BR sem_timedwait ()
103 never fails with a timeout error, regardless of the value of
104 .IR abs_timeout .
105 Furthermore, the validity of
106 .I abs_timeout
107 is not checked in this case.
108 .SH RETURN VALUE
109 All of these functions return 0 on success;
110 on error, the value of the semaphore is left unchanged,
111 \-1 is returned, and
112 .I errno
113 is set to indicate the error.
114 .SH ERRORS
116 .B EAGAIN
117 .RB ( sem_trywait ())
118 The operation could not be performed without blocking (i.e., the
119 semaphore currently has the value zero).
121 .B EINTR
122 The call was interrupted by a signal handler; see
123 .BR signal (7).
125 .B EINVAL
126 .I sem
127 is not a valid semaphore.
129 .B EINVAL
130 .RB ( sem_timedwait ())
131 The value of
132 .I abs_timeout.tv_nsecs
133 is less than 0, or greater than or equal to 1000 million.
135 .B ETIMEDOUT
136 .RB ( sem_timedwait ())
137 The call timed out before the semaphore could be locked.
138 .\" POSIX.1-2001 also allows EDEADLK -- "A deadlock condition
139 .\" was detected", but this does not occur on Linux(?).
140 .SH ATTRIBUTES
141 For an explanation of the terms used in this section, see
142 .BR attributes (7).
143 .ad l
146 allbox;
147 lbx lb lb
148 l l l.
149 Interface       Attribute       Value
151 .BR sem_wait (),
152 .BR sem_trywait (),
153 .BR sem_timedwait ()
154 T}      Thread safety   MT-Safe
158 .sp 1
159 .SH CONFORMING TO
160 POSIX.1-2001, POSIX.1-2008.
161 .SH EXAMPLES
162 The (somewhat trivial) program shown below operates on an
163 unnamed semaphore.
164 The program expects two command-line arguments.
165 The first argument specifies a seconds value that is used to
166 set an alarm timer to generate a
167 .B SIGALRM
168 signal.
169 This handler performs a
170 .BR sem_post (3)
171 to increment the semaphore that is being waited on in
172 .I main()
173 using
174 .BR sem_timedwait ().
175 The second command-line argument specifies the length
176 of the timeout, in seconds, for
177 .BR sem_timedwait ().
178 The following shows what happens on two different runs of the program:
180 .in +4n
182 .RB "$" " ./a.out 2 3"
183 About to call sem_timedwait()
184 sem_post() from handler
185 sem_timedwait() succeeded
186 .RB "$" " ./a.out 2 1"
187 About to call sem_timedwait()
188 sem_timedwait() timed out
191 .SS Program source
194 #include <unistd.h>
195 #include <stdio.h>
196 #include <stdlib.h>
197 #include <semaphore.h>
198 #include <time.h>
199 #include <assert.h>
200 #include <errno.h>
201 #include <signal.h>
203 sem_t sem;
205 #define handle_error(msg) \e
206     do { perror(msg); exit(EXIT_FAILURE); } while (0)
208 static void
209 handler(int sig)
211     write(STDOUT_FILENO, "sem_post() from handler\en", 24);
212     if (sem_post(&sem) == \-1) {
213         write(STDERR_FILENO, "sem_post() failed\en", 18);
214         _exit(EXIT_FAILURE);
215     }
219 main(int argc, char *argv[])
221     struct sigaction sa;
222     struct timespec ts;
223     int s;
225     if (argc != 3) {
226         fprintf(stderr, "Usage: %s <alarm\-secs> <wait\-secs>\en",
227                 argv[0]);
228         exit(EXIT_FAILURE);
229     }
231     if (sem_init(&sem, 0, 0) == \-1)
232         handle_error("sem_init");
234     /* Establish SIGALRM handler; set alarm timer using argv[1]. */
236     sa.sa_handler = handler;
237     sigemptyset(&sa.sa_mask);
238     sa.sa_flags = 0;
239     if (sigaction(SIGALRM, &sa, NULL) == \-1)
240         handle_error("sigaction");
242     alarm(atoi(argv[1]));
244     /* Calculate relative interval as current time plus
245        number of seconds given argv[2]. */
247     if (clock_gettime(CLOCK_REALTIME, &ts) == \-1)
248         handle_error("clock_gettime");
250     ts.tv_sec += atoi(argv[2]);
252     printf("main() about to call sem_timedwait()\en");
253     while ((s = sem_timedwait(&sem, &ts)) == \-1 && errno == EINTR)
254         continue;       /* Restart if interrupted by handler. */
256     /* Check what happened. */
258     if (s == \-1) {
259         if (errno == ETIMEDOUT)
260             printf("sem_timedwait() timed out\en");
261         else
262             perror("sem_timedwait");
263     } else
264         printf("sem_timedwait() succeeded\en");
266     exit((s == 0) ? EXIT_SUCCESS : EXIT_FAILURE);
269 .SH SEE ALSO
270 .BR clock_gettime (2),
271 .BR sem_getvalue (3),
272 .BR sem_post (3),
273 .BR sem_overview (7),
274 .BR time (7)