Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _GNU_SOURCE
- #include <string.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <dirent.h>
- #include <unistd.h>
- #include <sys/stat.h>
- #include <sys/msg.h>
- #include <sys/ipc.h>
- #include <sys/wait.h>
- #define FIFO_PATH "/tmp/dario%d.fifo"
- #define DIM_BUFFER 2048
- void reader(char *path, int pp){
- FILE *input;
- FILE *file;
- char buffer[DIM_BUFFER];
- if((input = fdopen(pp, "w")) == NULL){
- perror("fdopen pipe1");
- exit(1);
- }
- if((file = fopen(path, "r")) == NULL){
- perror("fopen fifo1");
- exit(1);
- }
- while(fgets(buffer, DIM_BUFFER, file)){
- fputs(buffer, input);
- }
- exit(0);
- }
- void filter(char *word, int pp, char *fifo, int i, int v){
- FILE *pipe_file;
- FILE *fifo_file;
- char buffer[DIM_BUFFER];
- if((pipe_file = fdopen(pp, "r")) == NULL){
- perror("fdopen pipe2");
- exit(1);
- }
- if((fifo_file = fopen(fifo, "w")) == NULL){
- perror("fopen fifo2");
- exit(1);
- }
- while(fgets(buffer, DIM_BUFFER, pipe_file)){
- /*if(buffer[strlen(buffer) - 1] == '\n')
- buffer[strlen(buffer) - 1] = '\0';*/
- if(i == 1){
- if(v == 0){
- if(strcasestr(buffer, word)){
- fputs(buffer, fifo_file);
- }
- }else if(v == 1){
- if(!strcasestr(buffer, word)){
- fputs(buffer, fifo_file);
- }
- }
- }else{
- if(v == 0){
- if(strstr(buffer, word)){
- fputs(buffer, fifo_file);
- }
- }else if(v == 1){
- if(!strstr(buffer, word)){
- fputs(buffer, fifo_file);
- }
- }
- }
- }
- exit(0);
- }
- void writer(char *fifo){
- FILE *fifo_file;
- char buffer[DIM_BUFFER];
- if((fifo_file = fopen(fifo, "r")) == NULL){
- perror("fopen fifo3");
- exit(1);
- }
- while(fgets(buffer, DIM_BUFFER, fifo_file)){
- printf("%s \n", buffer);
- }
- exit(0);
- }
- int main(int argc, char *argv[]){
- int pp[2];
- int v, i;
- v = i = 0;
- char fifopathname[DIM_BUFFER];
- int file, word;
- if(pipe(pp) == -1){
- perror("pipe");
- exit(1);
- }
- snprintf(fifopathname, DIM_BUFFER, FIFO_PATH, getpid());
- if(mkfifo(fifopathname, 0600) == -1){
- perror("fifo");
- exit(1);
- }
- if(strcmp(argv[1], "-i") == 0){
- i = 1;
- }
- if((i == 1 && (strcmp(argv[2], "-v") == 0)) || (i == 0 && (strcmp(argv[1], "-v") == 0))){
- v = 1;
- }
- if(i == 0 && v == 0){
- word = 1;
- }else if((i == 0 && v == 1) || (i == 1 && v == 0)){
- word = 2;
- }else if(i == 1 && v == 1){
- word = 3;
- }
- file = word + 1;
- if(fork() == 0){
- close(pp[0]);
- reader(argv[file], pp[1]);
- }
- if(fork() == 0){
- close(pp[1]);
- filter(argv[word], pp[0], fifopathname, i, v);
- }
- close(pp[0]);
- close(pp[1]);
- if(fork() == 0){
- writer(fifopathname);
- }
- wait(NULL);
- wait(NULL);
- wait(NULL);
- if (unlink(fifopathname) == -1) {
- perror(fifopathname);
- exit(1);
- }
- exit(0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement