Hi, I need to help with semafor implementation understanding. I meant I understood the logic of it based on available sources, but during implementation I am not able to get the desire outcome.
My goal is to lead with the help of semafor writing into pipes.
This is my implementation:
Code:
#include <stdio.h>#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
#define SEM_WRITE "SemaphorForControlWrite"
int main()
{
if(mkfifo("mySemaphorPipe", 0777) == -1)
{
if(errno != EEXIST)
{
printf("Something is wrong in Create...\n");
return 1;
}
}
sem_unlink(SEM_WRITE);
sem_t *sem_PipeWrite = sem_open(SEM_WRITE, IPC_CREAT, 0660, 0);
if(fork()==0)
{
// Create few children
fork();
fork();
fork();
while ( 1 )
{
sem_wait(sem_PipeWrite);
int fd = open("mySemaphorPipe", O_WRONLY);
if (fd == -1)
{
printf("Something is wrong in Open...\n");
return 1;
}
char buf[ BUFSIZ ];
srand(getpid());
sprintf( buf, "Process: %d - Send Number: %d", getpid(), rand() % 10000 );
if(write( fd, buf, strlen(buf))==-1)
{
printf("Write ERRoR of process %d\n", getpid());
fflush(stdout);
}
//sleep (1);
close(fd);
sem_post(sem_PipeWrite);
}
return 0;
}
printf("READ Pipe ... \n");
fflush(stdout);
while(1)
{
int fd = open("mySemaphorPipe", O_RDWR);
if (fd == -1)
{
printf("Something is wrong in Open...\n");
return 1;
}
char recievedData[1024]="";
if(read(fd, &recievedData, sizeof(recievedData)) == -1)
{
printf("Something is wrong in read...\n");
return 1;
}
printf("I get from pipe: %s", recievedData);
fflush(stdout);
close(fd);
}
return 0;
}
anzwaz if I use semafors, I will gain data only from one process and I cannot figure out where I am doing mistake in my logic.
Could I ask for help and need to explain where I am doing mistake and how to avoid it.