/*
 * fork02.c
 * 
 * Copyright 2026 osboxes <osboxes@osboxes>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * fork07 evita que existan procesos huerfanos
 * toma el retorno de los procesos hijos
 * asume que todos los fork() funcionan ok
 * usamos la funcion waitpid() para esperar por determinados pids
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

void quienSoy(pid_t,int);

int main(int argc, char **argv) {
	// proceso padre p1
	int a=-1;
	int estado=0,i;
	pid_t pids[2];
	pid_t pid = fork();
	if ( pid > 0 ) {
		pids[0]=pid;
		// proceso padre p1
		pid = fork();
		if ( pid > 0 ) {
			pids[1]=pid;
			// proceso padre p1
			a=0;
			quienSoy(pid,a);
			//¿cuantos wait() debo hacer aca? 2 xq tengo 2 hijos
			for(i=0;i<2;i++) {
				printf("p1 voy a esperar por pid=%d\n",pids[i]);
				pid=waitpid(pids[i],&estado,0);
				printf("Finalizo proceso %d retornando %d\n",pid,estado/256);
			}
		} else {
			// proceso hijo p1h2
			a=12;
			quienSoy(pid,a);
			//aca no debo hacer ningun wait() porque este es un hijo y no crea mas procesos
		}
	} else {
		// proceso hijo p1h1
		pid = fork();
		if ( pid > 0 ) {
			// proceso hijo p1h1
			a=11;
			quienSoy(pid,a);
			//¿cuantos wait() debo hacer aca? 1 xq solo creo a 1 proceso mas
			printf("p1h1 voy a esperar por pid=%d\n",pid);
			pid=waitpid(pid,&estado,0);
			printf("Finalizo proceso %d retornando %d\n",pid,estado/256);
		} else {
			// proceso hijo p1h1h1
			a=111;
			quienSoy(pid,a);
			//aca no debo hacer ningun wait() porque este es un hijo y no crea mas procesos
		}
	}
	printf("Soy proceso %d y termino devolviendo %d\n",getpid(),a);
	exit(a); //return 0;
}

void quienSoy(pid_t mipid,int numero) {
	printf("Soy proceso %d hijo de proceso %d fork devolvio %d a=%d\n",
		getpid(),getppid(),mipid,numero);
}
