1

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;

}
pramington
  • 51
  • 4

1 Answers1

0

Short answer: both your parent process and your child processes are spawning more children.

fork() returns twice - once in the parent, once in the child.

If you are the parent, you want to record the child pid and create more chidlren.

If you are the child, you want to go do some work. (Perhaps exec() some other executable.)

You distinguish these based on the return value from fork.

So:

sub_pids[i] = fork();
if (sub_pids[i] == 0) {
   /* child */
   ... get out of the loop here ...
} else if (sub_pids[i] == -1) {
   /* error */
   ... report the error here ...
} else {
   /* parent */
   ... nothing to do here, just continue the loop ...
}

[edit] I see you do have a correct looking fork() at the end of your code snippet. Perhaps that part needs to become a subroutine, called from the loops.

Also - you must create the pipe before forking. You have your creation loops before the call to pipe()

Arlie Stephens
  • 1,146
  • 6
  • 20