C - 带信号量的多个叉子

时间:2012-10-03 03:00:03

标签: c fork semaphore critical-section

我最终试图解决生产者 - 消费者问题,但我首先需要能够使用信号量创建一个关键部分。我目前遇到的问题是当我运行程序时,关键部分有时会有多个进程进入它。我想在给定时间只有一个进程处于临界区。这是我目前的代码:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

#define MAX 20

int main(void)
{
    key_t key = 1114;
    int semid, count,
        mutex = 0;


    //Initialize Semaphore Buffers
    struct sembuf oper0;

    pid_t waitId;
    pid_t parentId = getpid();

    //Create processes
    for(count = 0; count < MAX; count++)
    {
        if((waitId = fork()) == 0)
        {
            break;
        }
    }

    //Create a semaphore set of 3; I will be adding more semaphores
    if ((semid = semget(key, 3, 0600 | IPC_CREAT)) == -1) {
        printf("error in semget");
        exit(1);
    }

    // BINARY/MUTEX - initialize semaphore0 to 1 
    if(semctl(semid, mutex, SETVAL, 1) == -1)
    {
        printf("error in semctl");
        exit(0);
    }

    //Decrement semaphore 0
    oper0.sem_op = -1;
    oper0.sem_flg = 0;
    if (semop(semid, &oper0, 1) == -1) {
        printf("error decrementing semaphore \n");
        exit(1);
    }

    printf(" -- CRITICAL SECTION START ----------- \n\n");
    printf("%5d    %d     %s\n", getpid(), semctl(semid, 0, GETVAL, oper0.sem_num), " -- Semaphore 0");
    printf(" -- CRITICAL SECTION END -- \n\n");    

    //Increments semaphore 0
    oper0.sem_op = 1;
    oper0.sem_flg = 0;
    if (semop(semid, &oper0, 1) == -1) {
        printf("error incrementing semaphore \n");
        exit(1);
    }

    int i;
    if(getpid() == parentId)
    {
        for(i = 0; i < MAX i++)
        {
            wait(&waitId);
        }
    }
    else
    {
        exit(waitId);
    }

    // Remove semaphore 
    if (semctl(semid, 0, IPC_RMID) == -1) {
        printf("error in semctl");
        exit(1);
    }

    return 0;
}

以下是示例输出:

 -- CRITICAL SECTION START ----------- 

 1097    0      -- Semaphore 0
 -- CRITICAL SECTION END -- 

 -- CRITICAL SECTION START ----------- 

 1085    0      -- Semaphore 0
 -- CRITICAL SECTION END -- 

 -- CRITICAL SECTION START ----------- 

 -- CRITICAL SECTION START ----------- 

 1095    0      -- Semaphore 0
 -- CRITICAL SECTION END -- 

 1093    0      -- Semaphore 0
 -- CRITICAL SECTION END -- 

 -- CRITICAL SECTION START ----------- 

 -- CRITICAL SECTION START ----------- 

 1087    0      -- Semaphore 0
 -- CRITICAL SECTION END -- 

 1089    0      -- Semaphore 0
 -- CRITICAL SECTION END -- 

 -- CRITICAL SECTION START ----------- 

 1091    0      -- Semaphore 0
 -- CRITICAL SECTION END -- 

为什么信号量有时会锁定一个进程,有时它会让两个进程进入?

1 个答案:

答案 0 :(得分:3)

因为您在每个孩子中执行semctl(semid, mutex, SETVAL, 1)。你真的只想做一次。如果将fork循环移动到创建和初始化信号量的位置之后,您可能会发现它看起来好多了。

另外,你可能想在printf之后fflush(stdout);如果stdout被缓冲,那么即使缓冲区被写入临界区,输出仍可能最终混合。