#include<iostream>
#include<unistd.h>
#include<sys/wait.h>
#include<cstdlib>
#include<ctime>

void random_task(int id){
	srand(time(0));
	int delay = 1 + rand()%3;
	std::cout << "PID: " << getpid()\
	<< " | Task: " << id
	<<" | Delay: " << delay << "s\n";
	sleep(delay);
}

int main(){
	int total_tasks=10;
	int k=4;
	int pipefd[2];
	pipe(pipefd);

	pid_t root_pid=getpid();

	for (int w=0;w<k;w++) {
		fork();
	}

	if (getpid()!=root_pid) {
		close(pipefd[1]);
		int task;
		while (read(pipefd[0], &task, sizeof(task))>0) {
			random_task(task);
		}
		close(pipefd[0]);
		_exit(0);
	}

	close(pipefd[0]);
	for (int t=0;t<total_tasks;t++) {
		write(pipefd[1],&t,sizeof(t));
	}
	close(pipefd[1]);
	while(wait(0)>0);
	std::cout << "All tasks completed \n";
	return 0;
}
