Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <limits.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <string.h>
  6. #include <signal.h>
  7. #include <stdlib.h>
  8. #include <sys/wait.h>
  9.  
  10. int running = 0;
  11.  
  12. void handler(){
  13.     int status;
  14.     wait(&status);
  15.     if(WEXITSTATUS(status) == 1){
  16.         printf("Found! exiting..\n");
  17.         exit(0);
  18.     }
  19.     running--;
  20. }
  21.  
  22. int readln(int fp,char* buf,int size){
  23.  
  24.     char c;
  25.     int status;
  26.     int nbytes = 0;
  27.     while( (status = read(fp,&c,1)) > 0){
  28.  
  29.         if(status == -1) return -1;
  30.         buf[nbytes++] = c;
  31.         if(c == '\n') return nbytes;
  32.     }
  33.     return nbytes;
  34. }
  35.  
  36. void cleanBuf(char* buf,int size){
  37.     for(int i = 0; i < size; i++)
  38.         buf[i] = '\0';
  39. }
  40.  
  41. int main(int argc,char** argv){
  42.  
  43.     if(argc != 3){ perror("usage: ./findWord <word> <file>"); exit(-1); }
  44.  
  45.     struct sigaction act;
  46.     act.sa_handler = handler;
  47.     act.sa_flags = SA_NOCLDSTOP;
  48.     sigaction(SIGCHLD,&act,0);
  49.  
  50.     char* key = argv[1];
  51.     char* file = argv[2];
  52.  
  53.     int fp;
  54.     if( (fp = open(file,O_RDONLY)) == -1){ perror("error opening file"); exit(-1); }
  55.  
  56.  
  57.     char buffer[PIPE_BUF]; cleanBuf(buffer,PIPE_BUF);
  58.     while(readln(fp,buffer,PIPE_BUF) > 0){
  59.         int p[2];
  60.         pipe(p);
  61.         running++;
  62.         if(!fork()){
  63.             dup2(p[0],0); close(p[0]); close(p[1]);
  64.             execl("./find","./find",key,NULL);
  65.             perror("executing"); exit(-1); exit(-1);
  66.         }
  67.         close(p[0]);
  68.         write(p[1],buffer,strlen(buffer));
  69.         cleanBuf(buffer,PIPE_BUF);
  70.     }
  71.  
  72.     while(running);
  73.  
  74.     printf("Program never interrupted, not found\n");
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement