0

If I run code I get no result. If I delete sem_post and sem_wait then it works. I have a producer / consumer application which have exchanged data via shared memory.

#include<stdio.h>
#include<stdlib.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdbool.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <dispatch/dispatch.h>
#include <errno.h>
#include <math.h>

int shmid;
unsigned long long Fibonacci(int n);
typedef struct node_t {
  unsigned long long data;
  int n;
  bool set;
  int id;
} node_t;

typedef struct fibobuff_t {
   char szFiboText[BUFF_SIZE / 2];
   struct node_t naNode[MAX_BUF];
} fibobuff_t;

#define MAX_BUF 5
#define SHM_SIZE 65365
#define BUFF_SIZE 65536

sem_t *empty;
sem_t *full;

void producer(){
    int n =0, i =0;
    fibobuff_t *pFB = shmat(shmid, (void *) 0, 0);
    if(pFB == NULL){
        perror("error");
        exit(1);
    }
    while (true) {
        printf("(%i) Waiting for room... ", i);
        sem_wait(empty);  
        usleep(150 + rand() % 1350);   

        pFB->naNode[i].data = Fibonacci(n++);
        sem_post(full);
        i = (i + 1) % (MAX_BUF);
        if (pFB->naNode[i].set){
            //  sem_wait(empty);
        }
    }
}

void consumer(){
    fibobuff_t *pFB = shmat(shmid, (void *) 0, 0);
    int i = 0;
    while (true) { 
        printf("(%i) Waiting for content... ", i);
        sem_wait(full);

        usleep(150 + rand() % 1600);
        char szTmp[BUFF_SIZE/2] = {0};
        snprintf(szTmp, BUFF_SIZE/2, "%llu ", pFB->naNode[i].data);
        strncat(pFB->szFiboText,szTmp, BUFF_SIZE/2);
        pFB->naNode[i].set = FALSE;
        printf("\tNr. %i = %s\n\n", pFB->naNode[i].n, szTmp);
        i = (i + 1) % (BUFF_SIZE);
        sem_post(empty);
        //sem_post(pmut);
        if (!pFB->naNode[i].set){
            sem_wait(full);
        }
    }
}

int main(void)
{
    int t;
    if ((shmid = shmget(IPC_PRIVATE, BUFF_SIZE, 0666 | IPC_CREAT)) == -1) {
        perror("shmget consumer");
        exit(1);
    }
    fibobuff_t *pFB = shmat(shmid, (void *) 0, 0);

    for (t = 0; t < MAX_BUF; t++) {
        pFB->naNode[t].data = 0;
    }
    empty = sem_open("/empty",O_CREAT,0644,1);
    full = sem_open("/full",O_CREAT,0644,0);

    if(fork()){
        producer(); 
    }else{
        consumer();
    }
}

someone can help. I do not know what goes wrong

dragosht
  • 3,237
  • 2
  • 23
  • 32

1 Answers1

0
  • In consumer() you have two calls to sem_wait(full); drop the second one.

  • In consumer() you have i = (i + 1) % (BUFF_SIZE); correct is i = (i + 1) % MAX_BUF.

  • Note that subsequent runs of your program may behave differently from the first run, since you don't remove the semaphores by sem_unlink(), and their initial values are set when created.

Armali
  • 18,255
  • 14
  • 57
  • 171