/*
 * pipe01.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.
 * 
 * 
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char **argv) {
	int p[2];  // p[0] extremo de lectura
	           // p[1] extremo de escritura
	pipe(p);

	printf("pid(%d) proceso padre\n",getpid());
	pid_t pid = fork();
	if ( pid ) {
		//padre lector y escritor
		close(p[0]);
		// ahora el padre es SOLO escritor
		char *texto = "Hola Mundo Cruel!";
		int rc;
		while(*texto) {
			rc = write(p[1],texto,1);
			texto++;
		}
		close(p[1]);
		// el padre ya no es ni lector ni escritor
		// padre espera por la finalizacion del proceso hijo
		wait(0);
	} else {
		//hijo lector y escritor
		close(p[1]);
		// ahora el hijo es SOLO lector
		char letra;
		int rc=1;
		while(rc == 1) {
			rc = read(p[0],&letra,1);
			if ( rc == 1 ) printf("pid(%d) letra=%c\n",getpid(),letra);
		}
		printf("pid(%d) rc=%d\n",getpid(),rc);
		close(p[0]);
	}
	return 0;
}

