Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <signal.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <wait.h>
- void verifSig(int sig)
- {
- if(sig == SIGUSR1)
- {
- printf("C\n");
- }
- if(sig == SIGALRM)
- {
- printf("1\n");
- }
- alarm(1);
- }
- void handler(int sig)
- {
- if (sig==SIGCHLD)
- {
- pid_t pid;
- pid = wait(NULL);
- printf("Pid %d exited.\n", pid);
- }
- }
- int main(int argc, char* argv[])
- {
- if(argc != 3)
- {
- perror("nr gresit de arg");
- exit(1);
- }
- int pfd1[2], pfd2[2];
- int pid1, pid2, pid3;
- int fd1=open(argv[1],O_RDONLY);
- int fd2=open(argv[2],O_RDONLY);
- struct sigaction sigActAlarm;
- sigActAlarm.sa_handler = verifSig;
- sigActAlarm.sa_flags = 0;
- int rez;
- if((rez = sigaction(SIGALRM, &sigActAlarm, NULL)) < 0)
- {
- perror("eroare la sigalrm");
- exit(2);
- }
- if((rez = sigaction(SIGUSR1, &sigActAlarm, NULL)) < 0)
- {
- perror("eroare la sigusr1");
- exit(2);
- }
- struct sigaction sigActChld;
- sigActChld.sa_handler = handler;
- sigActChld.sa_flags = 0;
- if((fd1 < 0) || (fd2 < 0))
- {
- perror("eroare la deschidere fisiere");
- exit(2);
- }
- if((pipe(pfd1) < 0) || (pipe(pfd2) < 0))
- {
- perror("eroare la unul din pipes");
- exit(3);
- }
- //COPIL 1
- if((pid1 = fork()) < 0)
- {
- perror("nu s-a creat primul copil");
- exit(-1);
- }
- else if(pid1 == 0)
- {
- close(pfd1[0]);
- close(pfd2[1]);
- close(pfd2[0]);
- dup2(pfd1[1],1);
- execlp("cat", "cat", argv[1], NULL);
- printf("daca ajung aici, e eroare");
- exit(71);
- }
- //COPIL 2
- if((pid2 = fork()) < 0)
- {
- perror("nu s-a creat al doilea copil");
- exit(2);
- }
- else if(pid2 == 0)
- {
- close(pfd1[0]);
- close(pfd1[1]);
- close(pfd2[0]);
- dup2(pfd2[1],1);
- execlp("cat", "cat", argv[2], NULL);
- printf("daca ajung aici, e eroare");
- exit(72);
- }
- //COPIL 3
- if((pid3 = fork()) < 0)
- {
- perror("nu s-a creat al treilea copil");
- exit(2);
- }
- else if(pid3 == 0)
- {
- close(pfd1[1]);
- close(pfd2[1]);
- int nrc = 0;
- char buf1,buf2;
- printf("\n");
- while(read(pfd1[0], &buf1, 1) > 0)
- {
- if(buf1 >= '0' && buf1 <= '9')
- {
- nrc ++;
- kill(getppid(), SIGUSR1);
- }
- printf("%c", buf1);
- }
- printf("\n");
- while(read(pfd2[0], &buf2, 1) > 0)
- {
- if(buf2 >= '0' && buf2 <= '9')
- {
- nrc ++;
- kill(getppid(), SIGUSR1);
- }
- printf("%c", buf2);
- }
- printf("\n");
- exit(nrc);
- }
- if((rez = sigaction(SIGCHLD, &sigActChld, NULL)) > 0)
- {
- perror("eroare la sigchld");
- exit(2);
- }
- kill(getpid(),SIGCHLD);
- alarm(1);
- close(pfd1[0]);
- close(pfd1[1]);
- close(pfd2[0]);
- close(pfd2[1]);
- while(1);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement