/*
 * miloop.c
 * 
 * Copyright 2025 grchere <grchere@grci3>
 * 
 * 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.
 * 
 * Trabajo con conjunto de se#ales
 */


#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_sigusr1(int); 
void sig_sigusr2(int); 
void sig_sigint(int); 

// declaro conjunto de se#ales
sigset_t conjseniales;
int bloqueado = 0;
 
int main(int argc, char **argv)
{
	// inicializo vacio a este conjunto
	// conjseniales = {}
	sigemptyset(&conjseniales);
	// conjseniales = {SIGUSR1}
	sigaddset(&conjseniales,SIGUSR1);
	// conjseniales = {SIGUSR1,SIGUSR2}
	sigaddset(&conjseniales,SIGUSR2);

	// bloqueo ese conjunto de se#ales 
	sigprocmask(SIG_BLOCK,&conjseniales,NULL);
	bloqueado=1;
	signal(SIGUSR1,sig_sigusr1);
	signal(SIGUSR2,sig_sigusr2);
	signal(SIGINT,sig_sigint);
	
	//LOOP ETERNO
	while(1) {
		printf("main(): PID %d me bloqueo hasta recibir se#al\n",getpid());
		int ret = pause();
		printf("main(): pause() retorna %d\n",ret);
		if ( bloqueado ) {
			sigprocmask(SIG_BLOCK,&conjseniales,NULL);
		} else {
			sigprocmask(SIG_UNBLOCK,&conjseniales,NULL);
		}
	}
	return 0;
}

void sig_sigusr1(int signo) {
	printf("PID %d recibi SIGUSR1\n",getpid());
}
void sig_sigusr2(int signo) {
	printf("PID %d recibi SIGUSR2\n",getpid());
}
void sig_sigint(int signo) {
	// desbloqueo se#anles
	char *msg;
	if ( bloqueado ) {
		bloqueado = 0;
		msg = "desbloqueado";
	} else {
		bloqueado = 1;
		msg = "bloqueado";
	}
	printf("PID %d recibi SIGINT [%s]!\n",getpid(),msg);
}
