tdwig
tdwig

Reputation: 41

Setting up four processes with fork() using 1 pipe

Trying to write a simple program that uses pipe/fork to create/manage 1 parent and 4 kid processes. The parent process is supposed to display a main menu like so.

Main Menu:
1. Display children states
2. Kill a child
3. Signal a child
4. Reap a child
5. Kill and reap all children

The code I'm writing now is supposed to create 4 child processes. I'm unsure if I'm setting up the four child processes correctly. I understand fork returns 0 to the child and the PID to the parent. How do I access the parent for these PID values? Where exactly do I set up the menu for the parent process?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

#define BUFSIZE 1024
#define KIDS    4
main()
{
    //create unnamed pipe
    int fd[2];
    char buf[BUFSIZE];

    if (pipe(fd) < 0) 
    {
        perror("pipe failed");
        exit (1);
    }

    //array of child pids
    size_t child_pid[4]; 

    //create 4 proccesses 
    int i = 0;
    for (i = 0; i < KIDS; i++) {
        child_pid[i] = fork();
        if (child_pid[i]) {
            continue;
        } else if (child_pid[i] == 0) {
            close(fd[0]);
            printf("Child %d: pid: %zu", i+1, child_pid[i]);
            break;
        } else {
            printf("fork error\n");
            exit(1);
        }

    } 

}

My output is:

Child 1: pid: 0
Child 2: pid: 0
Child 3: pid: 0
Child 4: pid: 0

Upvotes: 0

Views: 667

Answers (1)

Armali
Armali

Reputation: 19375

I'm unsure if I'm setting up the four child processes correctly.

Right, you shouldn't let the children break out of their code block, so change

            break;

to

            sleep(99);  // or whatever you want the child to do
            exit(0);

How do I access the parent …?

There's getppid(), if for some reason you need it.

Where exactly do I set up the menu for the parent process?

Do that after the for loop before the end of main, that's where the parent continues execution.

Upvotes: 0

Related Questions