1sem_init(3)                Library Functions Manual                sem_init(3)
2
3
4

NAME

6       sem_init - initialize an unnamed semaphore
7

LIBRARY

9       POSIX threads library (libpthread, -lpthread)
10

SYNOPSIS

12       #include <semaphore.h>
13
14       int sem_init(sem_t *sem, int pshared, unsigned int value);
15

DESCRIPTION

17       sem_init()  initializes the unnamed semaphore at the address pointed to
18       by sem.  The value argument specifies the initial value for  the  sema‐
19       phore.
20
21       The  pshared  argument indicates whether this semaphore is to be shared
22       between the threads of a process, or between processes.
23
24       If pshared has the value 0, then the semaphore is  shared  between  the
25       threads  of  a  process,  and should be located at some address that is
26       visible to all threads (e.g., a global variable, or  a  variable  allo‐
27       cated dynamically on the heap).
28
29       If  pshared is nonzero, then the semaphore is shared between processes,
30       and should be located in a region of shared  memory  (see  shm_open(3),
31       mmap(2),  and  shmget(2)).   (Since a child created by fork(2) inherits
32       its parent's memory mappings, it can also access the  semaphore.)   Any
33       process  that  can  access  the shared memory region can operate on the
34       semaphore using sem_post(3), sem_wait(3), and so on.
35
36       Initializing a semaphore that has already been initialized  results  in
37       undefined behavior.
38

RETURN VALUE

40       sem_init() returns 0 on success; on error, -1 is returned, and errno is
41       set to indicate the error.
42

ERRORS

44       EINVAL value exceeds SEM_VALUE_MAX.
45
46       ENOSYS pshared is nonzero, but the system  does  not  support  process-
47              shared semaphores (see sem_overview(7)).
48

ATTRIBUTES

50       For  an  explanation  of  the  terms  used  in  this  section,  see at‐
51       tributes(7).
52
53       ┌────────────────────────────────────────────┬───────────────┬─────────┐
54Interface                                   Attribute     Value   
55       ├────────────────────────────────────────────┼───────────────┼─────────┤
56sem_init()                                  │ Thread safety │ MT-Safe │
57       └────────────────────────────────────────────┴───────────────┴─────────┘
58

STANDARDS

60       POSIX.1-2008.
61

HISTORY

63       POSIX.1-2001.
64
65       Bizarrely, POSIX.1-2001 does not specify the value that should  be  re‐
66       turned  by  a  successful  call  to sem_init().  POSIX.1-2008 rectifies
67       this, specifying the zero return on success.
68

EXAMPLES

70       See shm_open(3) and sem_wait(3).
71

SEE ALSO

73       sem_destroy(3), sem_post(3), sem_wait(3), sem_overview(7)
74
75
76
77Linux man-pages 6.04              2023-03-30                       sem_init(3)
Impressum