Sometimes this program errors with a segmentation fault. What is a segmentation fault? Why is it happening? And how do I fix it?
I am expecting the output as:
I am consumer
I am producer
I am consumer
I am producer
(etc.)
However, this is not the case. Can anyone explain this to me?
#include<stdio.h>
#include<semaphore.h>
#include<sys/stat.h>
#include<fcntl.h>
sem_t* mutex;
sem_t* null;
main()
{
int temp;
int pid;
pid = fork();
sem_unlink("/mutex");
sem_unlink("/null");
null = (sem_t*)sem_open("/null",O_CREAT,S_IWUSR|S_IWGRP|S_IWOTH,0);
mutex =(sem_t*)sem_open("/mutex",O_CREAT,S_IWUSR|S_IWGRP|S_IWOTH,1);
if (pid != 0)
while(1)
{
sem_post(null);
sem_wait(mutex);
printf("\nIam In Producer\n");
scanf("%d",&temp); // just for my verification that where i am during execution
sem_post(mutex);
sem_wait(null);
}
else
while(1)
{
sem_post(null);
sem_wait(mutex);
printf("\nIam In consumer\n");
scanf("%d",&temp); // just for my verification that where i am during execution
sem_post(mutex);
sem_wait(null);
}
}
I think you need to move the
sem_unlink()andsem_open()calls to before you callfork(). You’re probably unlinking things you don’t want to.Explanation – you call
fork(), now you have two processes running. Let’s say the parent gets through thesem_unlink()andsem_open()calls before the child gets any processor time. Now the child starts running, and immediately unlinks the parent’s semaphores!