【发布时间】:2019-07-28 12:09:47
【问题描述】:
我正在学习 POSIX 信号量。
编写了一个基本代码,允许在父子之间共享 POSIX 信号量。为什么子级更新后,父级的信号量值没有改变。
#include <stdio.h>
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
#include <stdlib.h>
void print_sem_value(sem_t *sem)
{
int sem_value;
if (sem_getvalue(sem, &sem_value) != 0) {
perror("sem_getvalue");
} else {
printf("%d:Semaphore value:%d\n", getpid(), sem_value);
}
}
int main(int argc, char *argv[])
{
pid_t pid;
sem_t sem;
sem_init(&sem, 1, 3);
pid = fork();
if (pid == 0) {
print_sem_value(&sem);
sem_wait(&sem);
print_sem_value(&sem);
sem_wait(&sem);
print_sem_value(&sem);
} else if (pid > 0) {
wait(NULL);
print_sem_value(&sem);
sem_post(&sem);
print_sem_value(&sem);
}
sem_destroy(&sem);
return 0;
}
【问题讨论】:
标签: c linux posix ipc semaphore