Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <limits.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <string.h>
- #include <signal.h>
- #include <stdlib.h>
- #include <sys/wait.h>
- int running = 0;
- void handler(){
- int status;
- wait(&status);
- if(WEXITSTATUS(status) == 1){
- printf("Found! exiting..\n");
- exit(0);
- }
- running--;
- }
- int readln(int fp,char* buf,int size){
- char c;
- int status;
- int nbytes = 0;
- while( (status = read(fp,&c,1)) > 0){
- if(status == -1) return -1;
- buf[nbytes++] = c;
- if(c == '\n') return nbytes;
- }
- return nbytes;
- }
- void cleanBuf(char* buf,int size){
- for(int i = 0; i < size; i++)
- buf[i] = '\0';
- }
- int main(int argc,char** argv){
- if(argc != 3){ perror("usage: ./findWord <word> <file>"); exit(-1); }
- struct sigaction act;
- act.sa_handler = handler;
- act.sa_flags = SA_NOCLDSTOP;
- sigaction(SIGCHLD,&act,0);
- char* key = argv[1];
- char* file = argv[2];
- int fp;
- if( (fp = open(file,O_RDONLY)) == -1){ perror("error opening file"); exit(-1); }
- char buffer[PIPE_BUF]; cleanBuf(buffer,PIPE_BUF);
- while(readln(fp,buffer,PIPE_BUF) > 0){
- int p[2];
- pipe(p);
- running++;
- if(!fork()){
- dup2(p[0],0); close(p[0]); close(p[1]);
- execl("./find","./find",key,NULL);
- perror("executing"); exit(-1); exit(-1);
- }
- close(p[0]);
- write(p[1],buffer,strlen(buffer));
- cleanBuf(buffer,PIPE_BUF);
- }
- while(running);
- printf("Program never interrupted, not found\n");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement