I'm trying to make a program that syncs 3 processes. The first process reads from the terminal and puts the string in a buffer, the second reads from the buffer and puts it in a second buffer, the third process reads from the second buffer and puts it in a file. Therefore, the access to the buffers should be managed using semaphores(one producer, one produccer/consumer and one consumer). The first process is a producer, second process is a producer/consumer and the third process is a consumer.
I've done everything I know about semaphores but it doesn't seem to work(probably I should use a shared memory?), what I've done so far is:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <semaphore.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char T0[6];
char T1[6];
int ip=0;
int ic=0;
int icp=0;
typedef struct sem
{
sem_t libre1;
sem_t libre2;
sem_t occupe1;
sem_t occupe2;
sem_t mutex1;
sem_t mutex2;
}sem_arg;
void lire(char *c)
{
read(0,c,sizeof(c));
}
int main()
{
sem_arg args;
sem_init(&args.libre1,0,6);
sem_init(&args.libre2,0,6);
sem_init(&args.occupe1,0,0);
sem_init(&args.occupe2,0,0);
sem_init(&args.mutex1,0,1);
sem_init(&args.mutex2,0,1);
pid_t p;
int i; int cmpt0=0,cmpt1=0,cmpt2=0;
char *c;
c=(char*)malloc(sizeof(char)*6);
char *c1;
c1=(char*)malloc(sizeof(char)*6);
for(i=1;i<3;i++)
{
if((p=fork())==0)
{
if(i==1)
{
while(cmpt1<6)
{
sem_wait(&args.libre2);
sem_wait(&args.occupe1);
sem_wait(&args.mutex1);
sem_wait(&args.mutex2);
T1[icp]=T0[ip];
icp=(icp+1)%6;
cmpt1++;
sem_post(&args.mutex1);
sem_post(&args.mutex2);
sem_post(&args.libre1);
sem_post(&args.occupe2);
}
}
else if(i==2)
{
FILE *fichier=fopen("prosecuss2.txt","w");
while(cmpt2<6)
{
sem_wait(&args.occupe2);
sem_wait(&args.mutex1);
fprintf(fichier,"%c\n",T1[ic]);
fflush(fichier);
ic=(ic+1)%6;
cmpt2++;
sem_post(&args.mutex1);
sem_post(&args.libre2);
}
}
}
}
while(cmpt0<6)
{
lire(c);
c1=encrypt(c);
sem_wait(&args.libre1);
sem_wait(&args.mutex1);
T0[ip]=*c1;
ip=(ip+1)%6;
cmpt0++;
sem_post(&args.mutex1);
sem_post(&args.occupe1);
}
return 0;
}
What is wrong in the program? Should I use threads instead?