Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <signal.h>
- #include <string.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <errno.h>
- static void handler (int);
- int main (int argc, char *argv[])
- {
- int fd;
- int pid;
- int num;
- char buf = 0;
- //Imposto il segnale
- signal (SIGUSR1,handler);
- //Apro e crea il file temporaneo controllo eventuali errori
- if (argc != 2) {
- printf("Hai inserito troppi numer1\n");
- exit(0);
- }
- if((fd = open("temp",O_RDWR | O_CREAT | O_TRUNC,0666)) < 0){
- perror("open\n");
- exit(1);
- }
- //Converto da carattere ad intero il numero passato da linea di comando
- num=atoi(argv[1]);
- write(fd,&buf,1);
- //Creo la fork per iniziare il processo figlio
- pid = fork();
- if (pid < 0) {
- perror("\nErrore creazione fork()!!!!\n");
- exit(1);
- }
- //Sono il figlio
- if (pid == 0) {
- //L'installazione handler viene ereditata
- printf("\nFiglio %d di padre %d\n",getpid(),getppid());
- //write(fd,buf,1);
- while ( buf < num )
- {
- read(fd,&buf,1);
- printf("FIGLIO\tleggo : %d\n",buf);
- lseek(fd,0,0); // 0 = SEE_SET !
- buf = ++buf;
- write(fd,&buf,1);
- printf("FIGLIO\tscrivo : %d\n",buf);
- lseek(fd,0,0);
- //invio il segnale al padre
- kill(getppid(),SIGUSR1);
- //Attendo il segnale
- pause();
- sleep(1);
- }
- exit(0);
- }
- //Padre
- printf("\nPadre %d figlio\n",getpid(),pid);
- pause();
- sleep(1);
- read(fd,&buf,1);
- while ( buf < num )
- {
- //Attesa iniziale
- printf("PADRE \tleggo : %d\n",buf);
- lseek(fd,0,SEEK_SET);
- buf = ++buf;
- write(fd,&buf,1);
- printf("PADRE \tscrivo : %d\n",buf);
- lseek(fd,0,SEEK_SET);
- //Invio il segnale al figlio
- kill(pid,SIGUSR1);
- pause();
- sleep(1);
- read(fd,&buf,1);
- }
- close (fd);
- exit(0);
- }
- //Gestisce una volta inviato il segnale
- static void handler (int signo)
- {
- if(signo == SIGUSR1)
- printf("\n####Scambio####\n");
- return;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement