Debian Codegraph @

upstream/debian-trixie/man3/sem_init.3

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