mbrtowc.3: SYNOPSIS: Use 'restrict' in prototypes
[man-pages.git] / man3 / sem_wait.3
blobd57b6f6ce4ff0e7a2d310b8f2a0834510cf9c61b
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 2020-06-09 "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 *" sem ", const struct timespec *" abs_timeout );
35 .fi
36 .PP
37 Link with \fI\-pthread\fP.
38 .PP
39 .RS -4
40 Feature Test Macro Requirements for glibc (see
41 .BR feature_test_macros (7)):
42 .RE
43 .PP
44 .BR sem_timedwait ():
45 .nf
46     _POSIX_C_SOURCE >= 200112L
47 .fi
48 .SH DESCRIPTION
49 .BR sem_wait ()
50 decrements (locks) the semaphore pointed to by
51 .IR sem .
52 If the semaphore's value is greater than zero,
53 then the decrement proceeds, and the function returns, immediately.
54 If the semaphore currently has the value zero,
55 then the call blocks until either it becomes possible to perform
56 the decrement (i.e., the semaphore value rises above zero),
57 or a signal handler interrupts the call.
58 .PP
59 .BR sem_trywait ()
60 is the same as
61 .BR sem_wait (),
62 except that if the decrement cannot be immediately performed,
63 then call returns an error
64 .RI ( errno
65 set to
66 .BR EAGAIN )
67 instead of blocking.
68 .PP
69 .BR sem_timedwait ()
70 is the same as
71 .BR sem_wait (),
72 except that
73 .I abs_timeout
74 specifies a limit on the amount of time that the call
75 should block if the decrement cannot be immediately performed.
76 The
77 .I abs_timeout
78 argument points to a structure that specifies an absolute timeout
79 in seconds and nanoseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
80 This structure is defined as follows:
81 .PP
82 .in +4n
83 .EX
84 struct timespec {
85     time_t tv_sec;      /* Seconds */
86     long   tv_nsec;     /* Nanoseconds [0 .. 999999999] */
88 .EE
89 .in
90 .PP
91 If the timeout has already expired by the time of the call,
92 and the semaphore could not be locked immediately,
93 then
94 .BR sem_timedwait ()
95 fails with a timeout error
96 .RI ( errno
97 set to
98 .BR ETIMEDOUT ).
99 .PP
100 If the operation can be performed immediately, then
101 .BR sem_timedwait ()
102 never fails with a timeout error, regardless of the value of
103 .IR abs_timeout .
104 Furthermore, the validity of
105 .I abs_timeout
106 is not checked in this case.
107 .SH RETURN VALUE
108 All of these functions return 0 on success;
109 on error, the value of the semaphore is left unchanged,
110 \-1 is returned, and
111 .I errno
112 is set to indicate the error.
113 .SH ERRORS
115 .B EINTR
116 The call was interrupted by a signal handler; see
117 .BR signal (7).
119 .B EINVAL
120 .I sem
121 is not a valid semaphore.
123 The following additional error can occur for
124 .BR sem_trywait ():
126 .B EAGAIN
127 The operation could not be performed without blocking (i.e., the
128 semaphore currently has the value zero).
130 The following additional errors can occur for
131 .BR sem_timedwait ():
133 .B EINVAL
134 The value of
135 .I abs_timeout.tv_nsecs
136 is less than 0, or greater than or equal to 1000 million.
138 .B ETIMEDOUT
139 The call timed out before the semaphore could be locked.
140 .\" POSIX.1-2001 also allows EDEADLK -- "A deadlock condition
141 .\" was detected", but this does not occur on Linux(?).
142 .SH ATTRIBUTES
143 For an explanation of the terms used in this section, see
144 .BR attributes (7).
145 .ad l
148 allbox;
149 lbx lb lb
150 l l l.
151 Interface       Attribute       Value
153 .BR sem_wait (),
154 .BR sem_trywait (),
155 .BR sem_timedwait ()
156 T}      Thread safety   MT-Safe
160 .sp 1
161 .SH CONFORMING TO
162 POSIX.1-2001, POSIX.1-2008.
163 .SH EXAMPLES
164 The (somewhat trivial) program shown below operates on an
165 unnamed semaphore.
166 The program expects two command-line arguments.
167 The first argument specifies a seconds value that is used to
168 set an alarm timer to generate a
169 .B SIGALRM
170 signal.
171 This handler performs a
172 .BR sem_post (3)
173 to increment the semaphore that is being waited on in
174 .I main()
175 using
176 .BR sem_timedwait ().
177 The second command-line argument specifies the length
178 of the timeout, in seconds, for
179 .BR sem_timedwait ().
180 The following shows what happens on two different runs of the program:
182 .in +4n
184 .RB "$" " ./a.out 2 3"
185 About to call sem_timedwait()
186 sem_post() from handler
187 sem_timedwait() succeeded
188 .RB "$" " ./a.out 2 1"
189 About to call sem_timedwait()
190 sem_timedwait() timed out
193 .SS Program source
196 #include <unistd.h>
197 #include <stdio.h>
198 #include <stdlib.h>
199 #include <semaphore.h>
200 #include <time.h>
201 #include <assert.h>
202 #include <errno.h>
203 #include <signal.h>
205 sem_t sem;
207 #define handle_error(msg) \e
208     do { perror(msg); exit(EXIT_FAILURE); } while (0)
210 static void
211 handler(int sig)
213     write(STDOUT_FILENO, "sem_post() from handler\en", 24);
214     if (sem_post(&sem) == \-1) {
215         write(STDERR_FILENO, "sem_post() failed\en", 18);
216         _exit(EXIT_FAILURE);
217     }
221 main(int argc, char *argv[])
223     struct sigaction sa;
224     struct timespec ts;
225     int s;
227     if (argc != 3) {
228         fprintf(stderr, "Usage: %s <alarm\-secs> <wait\-secs>\en",
229                 argv[0]);
230         exit(EXIT_FAILURE);
231     }
233     if (sem_init(&sem, 0, 0) == \-1)
234         handle_error("sem_init");
236     /* Establish SIGALRM handler; set alarm timer using argv[1]. */
238     sa.sa_handler = handler;
239     sigemptyset(&sa.sa_mask);
240     sa.sa_flags = 0;
241     if (sigaction(SIGALRM, &sa, NULL) == \-1)
242         handle_error("sigaction");
244     alarm(atoi(argv[1]));
246     /* Calculate relative interval as current time plus
247        number of seconds given argv[2]. */
249     if (clock_gettime(CLOCK_REALTIME, &ts) == \-1)
250         handle_error("clock_gettime");
252     ts.tv_sec += atoi(argv[2]);
254     printf("main() about to call sem_timedwait()\en");
255     while ((s = sem_timedwait(&sem, &ts)) == \-1 && errno == EINTR)
256         continue;       /* Restart if interrupted by handler. */
258     /* Check what happened. */
260     if (s == \-1) {
261         if (errno == ETIMEDOUT)
262             printf("sem_timedwait() timed out\en");
263         else
264             perror("sem_timedwait");
265     } else
266         printf("sem_timedwait() succeeded\en");
268     exit((s == 0) ? EXIT_SUCCESS : EXIT_FAILURE);
271 .SH SEE ALSO
272 .BR clock_gettime (2),
273 .BR sem_getvalue (3),
274 .BR sem_post (3),
275 .BR sem_overview (7),
276 .BR time (7)