锁定C中的信号量问题sys/sem

锁定C中的信号量问题sys/sem,c,semaphore,C,Semaphore,编辑:这种代码的平静是非常好的(所以以它作为信号量的例子;)。我的程序中的Bug在另一个地方——被我的朋友发现了 我的功能有问题。有时两个过程进入临界区。在我花了10个小时调试之后,我没有发现这个问题。我应该瞄准什么?有没有可能在这段代码中包含bud 动作循环: // semaphores init int mutex; if ((mutex=semget(key+2, 1, 0666))>=0) { // semaphore exists fprintf(stderr,"

编辑:这种代码的平静是非常好的(所以以它作为信号量的例子;)。我的程序中的Bug在另一个地方——被我的朋友发现了

我的功能有问题。有时两个过程进入临界区。在我花了10个小时调试之后,我没有发现这个问题。我应该瞄准什么?有没有可能在这段代码中包含bud

动作循环:

// 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);
}   
请随意编辑我的问题


非常感谢

在你的“动作循环”中,如果你的信号量不存在,你会怎么做

目前,semget的第三个参数是0666或PERMISSION\u RW常量。您可能需要使用:

shmget(键,1,权限| IPC |创建)


这样,如果您的信号量不存在,它将创建一个。

那么bug在另一个地方…

您可能需要测试p()和V()的返回值?get_val()的定义是什么?你真的在测试正确的东西吗?发布一个完整的编译和运行的简化程序及其输出。我猜您没有正确初始化信号量。别让我们猜了。发布了更多细节@edgar.holleis:stderr是空的,所以V和P可以正常工作。
// 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);
}