I'm trying to write a program that forks a server process, n publisher processes, m subscriber processes, create a pipe with each publisher and subscriber process, and listen for info on each pipe. I've done a little bit of work but I don't quite know what I need to do make the code I've written complete.
One thing that is definitely wrong is that much more than m subscriber processes are being forked. Why is this happening and how can I fix it?
Any advice would be much appreciated!
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
int num_publishers = 0;
int num_subscribers = 0;
int main(int argc, char *argv[])
{
int pfds[2];
char buf[128];
num_publishers = atoi(argv[1]);
num_subscribers = atoi(argv[2]);
printf("%d publishers and %d subscribers.\n", num_publishers, num_subscribers);
pid_t pub_pids[num_publishers];
pid_t sub_pids[num_subscribers];
for (int i=0; i < num_publishers; i++)
{
pub_pids[i] = fork();
printf("Publisher: %d \n", pub_pids[i]);
}
printf("\n");
for (int i=0; i < num_subscribers; i++)
{
sub_pids[i] = fork();
printf("Subscriber: %d \n", sub_pids[i]);
}
printf("\n");
pipe(pfds);
if (!fork())
{
printf("CHILD: writing to the pipe\n");
write(pfds[1], );
printf("CHILD: exiting\n");
exit(0);
}
else
{
printf("PARENT: reading from pipe\n");
read(pfds[0], buf, 5);
printf("PARENT: read \"%s\"\n", buf);
wait(NULL);
}
return 0;
}