/*
 * 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
 */
#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;
	pid_t pid = fork();
	if ( pid > 0 ) {
		// proceso padre p1
		pid = fork();
		if ( pid > 0 ) {
			// proceso padre p1
			a=0;
			quienSoy(pid,a);
			//¿cuantos wait() debo hacer aca? 2 xq tengo 2 hijos
			wait(0);
			wait(0);
		} 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
			wait(0);
		} 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);
	//sleep(2);
	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);
}
