]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man3/sem_init.3
All pages: Replace the 4th argument to .TH by "Linux man-pages (unreleased)"
[thirdparty/man-pages.git] / man3 / sem_init.3
1 .\" Copyright (C) 2006 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\"
3 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
4 .\"
5 .TH SEM_INIT 3 2021-03-22 "Linux man-pages (unreleased)" "Linux Programmer's Manual"
6 .SH NAME
7 sem_init \- initialize an unnamed semaphore
8 .SH LIBRARY
9 POSIX threads library
10 .RI ( libpthread ", " \-lpthread )
11 .SH SYNOPSIS
12 .nf
13 .B #include <semaphore.h>
14 .PP
15 .BI "int sem_init(sem_t *" sem ", int " pshared ", unsigned int " value );
16 .fi
17 .SH DESCRIPTION
18 .BR sem_init ()
19 initializes the unnamed semaphore at the address pointed to by
20 .IR sem .
21 The
22 .I value
23 argument specifies the initial value for the semaphore.
24 .PP
25 The
26 .I pshared
27 argument indicates whether this semaphore is to be shared
28 between the threads of a process, or between processes.
29 .PP
30 If
31 .I pshared
32 has the value 0,
33 then the semaphore is shared between the threads of a process,
34 and should be located at some address that is visible to all threads
35 (e.g., a global variable, or a variable allocated dynamically on
36 the heap).
37 .PP
38 If
39 .I pshared
40 is nonzero, then the semaphore is shared between processes,
41 and should be located in a region of shared memory (see
42 .BR shm_open (3),
43 .BR mmap (2),
44 and
45 .BR shmget (2)).
46 (Since a child created by
47 .BR fork (2)
48 inherits its parent's memory mappings, it can also access the semaphore.)
49 Any process that can access the shared memory region
50 can operate on the semaphore using
51 .BR sem_post (3),
52 .BR sem_wait (3),
53 and so on.
54 .PP
55 Initializing a semaphore that has already been initialized
56 results in undefined behavior.
57 .SH RETURN VALUE
58 .BR sem_init ()
59 returns 0 on success;
60 on error, \-1 is returned, and
61 .I errno
62 is set to indicate the error.
63 .SH ERRORS
64 .TP
65 .B EINVAL
66 .I value
67 exceeds
68 .BR SEM_VALUE_MAX .
69 .TP
70 .B ENOSYS
71 .I pshared
72 is nonzero,
73 but the system does not support process-shared semaphores (see
74 .BR sem_overview (7)).
75 .SH ATTRIBUTES
76 For an explanation of the terms used in this section, see
77 .BR attributes (7).
78 .ad l
79 .nh
80 .TS
81 allbox;
82 lbx lb lb
83 l l l.
84 Interface Attribute Value
85 T{
86 .BR sem_init ()
87 T} Thread safety MT-Safe
88 .TE
89 .hy
90 .ad
91 .sp 1
92 .SH STANDARDS
93 POSIX.1-2001.
94 .SH NOTES
95 Bizarrely, POSIX.1-2001 does not specify the value that should
96 be returned by a successful call to
97 .BR sem_init ().
98 POSIX.1-2008 rectifies this, specifying the zero return on success.
99 .SH EXAMPLES
100 See
101 .BR shm_open (3)
102 and
103 .BR sem_wait (3).
104 .SH SEE ALSO
105 .BR sem_destroy (3),
106 .BR sem_post (3),
107 .BR sem_wait (3),
108 .BR sem_overview (7)