/*
 * admin.c
 * 
 * Copyright 2023 grchere <grchere@grcnet>
 * 
 * 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.
 *
 * Proceso que coordina a otros dos procesos independientes (may, min)
 * que graban letras mayusculas y minusculas dentro de archivo Abecedario
 * Los procesos subordinados graban en archivo pids los PID de cada uno
 * de ellos
 * Estructura archivo pids:
 * 	2 registros de longitud fija de sizeof(pid_t) bytes
 *  1er registro tiene el PID de proceso mayusculas
 *  2do registro tiene el PID de proceso minusculas
 * Estructura archivo Abecedario:
 *  AbCdEfGh... hasta la Z/z
 * 
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char **argv) {
	printf("main(): admin inicio\n");
    // creo archivo pids
    int fd = open("pids",O_CREAT|O_TRUNC|O_WRONLY,0666);
    int bytes = sizeof(pid_t)*2;
    int i;
    char c = 0;
    for(i=0;i<bytes;i++) {
		write(fd,&c,1);
	}
    close(fd);	
	// creo archivo Abecedario vacio
    fd = open("Abecedario",O_CREAT|O_TRUNC|O_WRONLY,0666);
    close(fd);	
	// espero, loop hasta que ambos PID's contengan algo 
	pid_t pidMay, pidMin;
	do {
		fd = open("pids",O_RDONLY);
		read(fd,&pidMay,sizeof(pid_t));
		read(fd,&pidMin,sizeof(pid_t));
		close(fd);
		//TRACE
		printf("main(): leid pidMay=%d pidMin=%d\n",pidMay,pidMin);
	} while(pidMay == 0 || pidMin == 0);
	// se supone que pidMay y pidMin son disintos de cero
	//TRACE
	printf("main(): pidMay=%d pidMin=%d\n",pidMay,pidMin);
	// envio se#ales a los procesos escritores de abcedario
	//char letra = 'a';
	//while(letra <= 'z') {
	int kmay=0,kmin=0;
	do {
		kill(pidMay,SIGUSR1);
		kill(pidMin,SIGUSR1);
		// envio se#ales nulas a los procesos para ver si aun existen
		kmay = kill(pidMay,0);
		kmin = kill(pidMin,0);
	} while(kmay == 0 || kmin == 0);
	//TRACE
	printf("main(): kmay=%d kmin=%d ambos procesos han terminado\n",kmay,kmin);
	
	// matamos procesos escritores
	//kill(pidMay,SIGKILL);
	//kill(pidMin,SIGKILL);
	//TRACE
	//remove("pids");
	printf("main(): fin\n");
	return 0;
}
