I'm trying to fix this code instead of using threads and locks i am using parent and child process with fork() method. But only the producer method is producing and the consumer isn't consuming anything. I looked it up and found that they are not sharing the same memory space. As if they are two separate buffers. I want to make the use the same buffer. Can anyone help me with this? i am using terminal Linux
#include <iostream>
#include <queue>
#include <condition_variable>
#include <unistd.h>
#include <chrono>
using namespace std ;
std::queue<int> buffer;
std::condition_variable cv;
int emptybuffer=5; //checks if there is any empty slots
int fullbuffer=0; // checks if there is any full slots
void producer()
{ int i=1;
while(emptybuffer>0)
{
buffer.push(i);
std::cout << "Produced: " << i << std::endl;
i++;
emptybuffer--;
fullbuffer++;
}
usleep(1000 * 1000); // 500 milliseconds
}
void consumer() {
while (fullbuffer>0)
{
int data = buffer.front();
buffer.pop();
std::cout << "Consumed: " << data << std::endl;
emptybuffer++;
fullbuffer--;
}
// Sleep to simulate some work being done
usleep(1000 * 1000); // 1000 milliseconds
}
int main()
{
pid_t c_pid = fork();
if (c_pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
else if (c_pid > 0) {
// wait(nullptr);
producer();
cout << "printed from parent process " << getpid()
<< endl;
exit(0);
}
else {
consumer();
cout << "printed from child process " << getpid()
<< endl;
exit(0);
}
return 0;
}