【发布时间】:2019-05-09 16:58:31
【问题描述】:
我正在尝试为 POSIX 标准重构我的 C 代码。显然我遇到了死锁,这归结为这个简单的代码。信号量应该在两个进程之间共享,但不幸的是它由创建它的进程所有。
创作者
sem_t * mutex;
if ((mutex = sem_open (key_trucker, O_CREAT, 0644, 1)) == SEM_FAILED) {
perror ("sem_open"); exit (1);
}
int val;
sem_getvalue(mutex,&val);
if(val == 0 ){
sem_post(mutex);
}
time_t currtime;
while(1){
sem_wait(mutex);
time(&currtime);
sleep(1);
printf("%s",ctime(&currtime) );
sem_post(mutex);
}
共享信号量的进程
sem_t * mutex;
if ((mutex = sem_open (key_trucker, 0 )) == SEM_FAILED) {
perror ("sem_open"); exit (1);
}
time_t currtime;
while(1){
sem_wait(mutex);
time(&currtime);
printf("%s",ctime(&currtime) );
sleep(1);
sem_post(mutex);
}
【问题讨论】: