编辑:这段代码非常好(所以把它作为信号量的例子;)。我程序中的错误在另一个地方 - 由我的 friend 发现。
我的功能有问题。有时两个进程进入临界区。我花了10个小时调试后找不到问题。我应该瞄准什么?这段代码有没有可能有bud?
// lock semaphore
static int P(int sem_id)
{
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = -1; /* P() */
sem_b.sem_flg = 0;
if (semop(sem_id, &sem_b, 1) == -1) {
// error
return(0);
}
return(1);
}
// unlock semaphore
static int V(int sem_id)
{
struct sembuf sem_b[1];
sem_b.sem_num = 0;
sem_b.sem_op = 1; /* V() */
sem_b.sem_flg = 0;
if (semop(sem_id, &sem_b, 1) == -1) {
// error
return(0);
}
return(1);
}
static int set_semval(int sem_id) {
// set to 1 (opened semaphore)
if (semctl(sem_id, 0, SETVAL, 1) == -1) {
// error
return(0);
}
return(1);
}
static int get_val(int sem_id)
{
union semun sem_union;
//sem_union.val = 0; ?
return semctl(sem_id, 0, GETVAL, sem_union);
}
Action 循环:
// semaphores init
int mutex;
if ((mutex=semget(key+2, 1, 0666))>=0) {
// semaphore exists
fprintf(stderr,"semaphore exists for key %d\n", key+2);
}
if ((mutex=semget(key+2, 1, 0666 | IPC_CREAT)) == -1) {
exit(EXIT_FAILURE);
}
if (!set_semval(mutex)) {
exit(EXIT_FAILURE);
}
fork() // some times with good conditionals
// in some children
while(1) {
P(mutex);
assert(get_val(mutex)==0); // always ok
action(); // sometimes made by two processes at same time - fault
V(mutex);
}
请随时编辑我的问题。
非常感谢
最佳答案
在您的“ Action 循环”中,如果您的信号量不存在,您会怎么做?
目前,您传递给 semget 的第三个参数是 0666 或 PERMISSION_RW 常量。你可能想使用:
shmget(key, 1, PERMISSION_RW | IPC_CREAT);
这样,如果您的信号量不存在,它将创建一个。
关于c - 在 C 问题 sys/sem 中锁定信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2739043/