/*
 * may.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 escritor de mayusculas en archivo Abecedario
 * coordinado por proceso admin
 * 
 * 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>

void sig_usr1(int); 

char letra = 'A';
int fd;

int main(int argc, char **argv) {
	printf("main(): may inicio\n");
	signal(SIGUSR1,sig_usr1);
	
    // creo archivo pids
    fd=0;
    printf("main(): may intento open de archivo pids\n");
    do {
		fd = open("pids",O_RDWR);
	} while(fd == -1);
    printf("main(): may logre abrir archivo pids\n");
    pid_t pid = getpid();
    write(fd,&pid,sizeof(pid_t));
    close(fd);
    printf("main(): may grabe mi PID %d en archivo pids\n",pid);

	// abro archivo Abecedario
    printf("main(): may intento abrir archivo Abecedario\n");
	do {
		fd = open("Abecedario",O_RDWR);
	} while(fd == -1);
    printf("main(): may abri archivo Abecedario\n");
	// espero, loop hasta que escriba todas las letras mayusculas
	while(letra <= 'Z') {
		pause();
		off_t pos = letra - 'A';
		off_t lret = lseek(fd,pos,SEEK_SET);
		int ret = write(fd,&letra,1);
		//TRACE
		printf("main(): may grabe %c en %ld write()=%d lseek()=%ld\n",letra,pos,ret,lret);
		letra+=2;
	}
    close(fd);	
	printf("main(): may grabe todas las letras!\n");
	printf("main(): may fin\n");
	return 0;
}

void sig_usr1(int signo) {
	if ( letra > 'Z' ) return;
}
