### Esempio di due processi concorrenti, pipe e exec ###
### By Lord_Dex - f.apollonio@salug.it ###

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>

void handler(int signum);

int main(int argc, char **argv){	

	signal(SIGCHLD, handler);

	int pp[2];
	pipe(pp);

	int pid[2];

	pid[0] = fork();

	if (pid[0]==0) {
		//FIGLIO1
		sleep(1);
		close(pp[0]); close(1);
		dup(pp[1]);
		execl("/bin/ls", "ls", (char*)0);
		perror("\tFIGLIO1: Errore in execl:");
		exit(1);
	} else {
		pid[1] = fork();
		if (pid[1]==0) {
			//FIGLIO2
			sleep(2);
			//close(pp[1]);
			char buff; int br=0;
			char string[] = "\tFIGLIO2: \n";
			write(1, string, strlen(string));
			while ( (br=read(pp[0], &buff, 1)) > 0 ) {
				write(1, &buff, 1);
			}
			close(pp[0]);
		} else {
			//PADRE	
			printf("\tPADRE: figli avviati, %d %d\n", pid[0], pid[1]);
			close(pp[0]); close(pp[1]);
			int figli=2;
			while(figli!=0) {
				--figli;
				pause();
			}
		}
	}

	return 0;

}

void handler(int signum) {
	signal(SIGCHLD, handler);
	int status;
	printf("\tPADRE: stoppo figlio!\n");
	wait(&status);
}

