/*
 * ej2.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.
 * 
 * primer intento de shell en foreground & background
 * input de teclado, fork, exec
 * problema: cuando hago fgets() el shell esta bloqueado y no hay 
 * forma de verificar la finalizacion de procesos background
 * utilizamos se#al de alarma para verificar cada N segundos
 * la finalizacion de procesos
 * Usar la se#al de alarma para verificar la finalizacion de los
 * procesos background no es una solucion eficiente
 * Mejor utilizar la se#al SIGCHLD que es recibida por el padre
 * cada vez que finzaliza un proceso hijo
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char **argv) {
	int m[4][3] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
	int t[4],tg=0,i;
	pid_t pid[4],p;
	for(i=0;i<4;i++) {
		p=fork();
		if ( p != 0 && p != -1 ) pid[i]=p;
		else {
			char *pcmd[5];
			pcmd[0] = "./sumar";
			int z;
			char tmp[10];
			for(z=1;z<=3;z++) {
				snprintf(tmp,10,"%d",m[i][z-1]);
				pcmd[z] = strdup(tmp);
			}
			pcmd[z]=NULL;
			execvp(pcmd[0],pcmd);
			printf("Error ejecutando ./sumar\n");
			exit(-1);
		}
	}
	
	for(i=0;i<4;i++) {
		int estado=0;
		t[i]=0;
		if ( waitpid(pid[i],&estado,0) != -1 ) {
			t[i] = estado / 256;
			tg+=t[i];
			printf("Total fila %d = %d\n",i,t[i]);
		}
	}
	printf("Total General %d\n",tg);
	return 0;
}
