Digamos que tenedor N niños. Quiero crear tuberías entre 1 y 2, 2 y 3, 4 y 5, ... y así sucesivamente. Así que necesito alguna manera de averiguar qué niño es cuál. El siguiente código es lo que tengo actualmente. Solo necesito alguna forma de saber que el niño número n es el niño número n.
int fd[5][2]; int i; for(i=0; i<5; i++) { pipe(fd[i]); } int pid = fork(); if(pid == 0) { }El siguiente código creará una tubería para cada hijo, bifurcará el proceso tantas veces como sea necesario y enviará del padre a cada hijo un valor int (la identificación que queremos darle al hijo), finalmente los hijos leerán el valor y terminación.
Nota: dado que está bifurcando, la variable i contendrá el número de iteración, si el número de iteración es la identificación del niño, entonces no necesita usar la tubería.
#include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]) { int count = 3; int fd[count][2]; int pid[count]; // create pipe descriptors for (int i = 0; i < count; i++) { pipe(fd[i]); // fork() returns 0 for child process, child-pid for parent process. pid[i] = fork(); if (pid[i] != 0) { // parent: writing only, so close read-descriptor. close(fd[i][0]); // send the childID on the write-descriptor. write(fd[i][1], &i, sizeof(i)); printf("Parent(%d) send childID: %d\n", getpid(), i); // close the write descriptor close(fd[i][1]); } else { // child: reading only, so close the write-descriptor close(fd[i][1]); // now read the data (will block) int id; read(fd[i][0], &id, sizeof(id)); // in case the id is just the iterator value, we can use that instead of reading data from the pipe printf("%d Child(%d) received childID: %d\n", i, getpid(), id); // close the read-descriptor close(fd[i][0]); //TODO cleanup fd that are not needed break; } } return 0; }