#include <semaphore.h>
sem_t *sem_open(const char *name, int oflag);
sem_t *sem_open(const char *name, int oflag,
mode_t mode, unsigned int value);
sem_open() creates a new POSIX semaphore or opens an existing semaphore.
The oflag argument specifies flags that control the operation of the call. If
O_CREAT is specified in oflag, then the semaphore is created if it does not already
exist. The owner (user ID) of the semaphore is set to the effective user ID of the
calling process. The group ownership (group ID) is set to the effective group ID of
the calling process. If both O_CREAT and O_EXCL are specified in oflag, then an
error is returned if a semaphore with the given name already exists.
The mode argument specifies the permissions to be placed on the new semaphore, as for
open(2)
The value argument specifies the initial value for the new semaphore.
note:If O_CREAT is specified, and a semaphore with the given name already exists, then mode
and value are ignored.
1
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <semaphore.h>
6
7 int main(void)
8 {
9 sem_t *sem;
10
11 sem = sem_open("随便", O_CREAT, 0777, 3);
12 if (sem == SEM_FAILED)
13 {
14 perror("sem_open");
15 return 1;
16 }
17
18 return 0;
19 }
int sem_unlink(const char *name);
sem_unlink() removes the named semaphore referred to by sem.
1
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <semaphore.h>
5
6 int main(void)
7 {
8 sem_unlink("随便");
9
10 return 0;
11 }
int sem_post(sem_t *sem);
sem_post() increments (unlocks) the semaphore pointed to by sem. If the semaphore’s
value consequently becomes greater than zero, then another process or thread blocked
in a sem_wait(3) call will be woken up and proceed to lock the semaphore.
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <semaphore.h>
6
7 int main(void)
8 {
9 sem_t *sem;
10
11 sem = sem_open("随便", 0);
12 if (sem == SEM_FAILED)
13 {
14 perror("sem_open");
15 return 1;
16 }
17
18 sem_post(sem);
19
20 return 0;
21 }
int sem_wait(sem_t *sem);
int sem_trywait(sem_t *sem);
sem_wait() decrements (locks) the semaphore pointed to by sem. If the semaphore’s
value is greater than zero, then the decrement proceeds, and the function returns,
immediately. If the semaphore currently has the value zero, then the call blocks
until either it becomes possible to perform the decrement (i.e., the semaphore value
rises above zero), or a signal handler interrupts the call.
1
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <semaphore.h>
6
7 int main(void)
8 {
9 sem_t *sem;
10
11 sem = sem_open("随便", 0);
12 if (sem == SEM_FAILED)
13 {
14 perror("sem_open");
15 return 1;
16 }
17
18 sem_wait(sem);
19 printf("after sem_wait\n");
20
21 return 0;
22 }
notice : gcc *.c -lrt