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
printf("Child %d: pid: %zu", i+1, child_pid[i]);
works just fine. It is only executed whenchild_pid[i] == 0
, and this is exactly what it does (ie it prints a zero). The error is in your concept. – sokin