0
votes

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
1
Was there any error? How many times does it loop? and where is this declared "pid"?artsylar
Sorry I was changing around that loop so much I messed that up, it's supposed to be child_pid[i]. I am editing in the output I'm getting.tdwig
The printf("Child %d: pid: %zu", i+1, child_pid[i]); works just fine. It is only executed when child_pid[i] == 0, and this is exactly what it does (ie it prints a zero). The error is in your concept.sokin
HINT: Is there a way for a process to get its own pid ?sokin

1 Answers

0
votes

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.