Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <limits.h>
  4. #include <string.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <fcntl.h>
  9. #include <signal.h>
  10. #include <sys/wait.h>
  11.  
  12. void cleanBuf(char* buf,int size){
  13. for(int i = 0; i < size; i++)
  14. buf[i] = '\0';
  15. }
  16.  
  17. int readLine(int fp,char* buf,int size){
  18. char c;
  19. int status;
  20. int nbytes = 0;
  21. while( (status = read(fp,&c,1)) > 0){
  22. if(status == -1) return -1;
  23. else if(c == '\n') return nbytes;
  24. else buf[nbytes++] = c;
  25. }
  26. return nbytes;
  27. }
  28.  
  29. int main(int argc,char** argv){
  30. if(argc != 2){ perror("usage: ./countLines <file name>"); exit(-1); }
  31.  
  32. int p[2];
  33. pipe(p);
  34. pid_t pid;
  35.  
  36. int fp = open(argv[1],O_RDONLY);
  37. if(fp == -1){ perror("error opening file\n"); exit(-1); }
  38. char buffer[PIPE_BUF]; cleanBuf(buffer,PIPE_BUF);
  39. char line[PIPE_BUF]; cleanBuf(line,PIPE_BUF);
  40.  
  41. if( (pid = fork()) == 0){
  42. dup2(p[0],0); close(p[0]); close(p[1]);
  43. execl("./wc","./wc",NULL);
  44. exit(-1);
  45. }
  46. else {
  47. close(p[0]);
  48. int r;
  49. while((r = readLine(fp,buffer,PIPE_BUF)) > 0){
  50. write(p[1],buffer,strlen(buffer));
  51. cleanBuf(buffer,PIPE_BUF);
  52. }
  53. }
  54.  
  55. close(p[1]);
  56. wait(NULL);
  57.  
  58. kill(pid,SIGKILL);
  59.  
  60. return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement