Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6.  
  7. void err_sys(const char* x) { perror(x); exit(1); }
  8.  
  9. void upper(char *s) { while((*s = toupper(*s))) ++s; }
  10.  
  11. void filter(int input, int output)
  12. {
  13. char buff[1024];
  14. bzero(buff, sizeof(buff));
  15. size_t n = read(input, buff, sizeof(buff));
  16.  
  17. printf("process %ld: got '%s'\n", (long) getpid(), buff);
  18.  
  19. upper(buff);
  20. write(output, buff, strlen(buff));
  21. }
  22.  
  23. void filter2(int input, int output)
  24. {
  25. if (dup2(input, 0) != 0) err_sys("dup2(input, 0)");
  26. if (dup2(output, 1) != 1) err_sys("dup2(output, 1)");
  27. execlp("/usr/bin/tr", "tr", "[a-z]", "[A-Z]" , (char*)0);
  28. }
  29.  
  30. int main(int argc, char** argv)
  31. {
  32. int pipe1[2];
  33. int pipe2[2];
  34. if (pipe(pipe1) < 0) err_sys("pipe1");
  35. if (pipe(pipe2) < 0) err_sys("pipe2");
  36.  
  37. pid_t pid;
  38. if ((pid = fork()) < 0) err_sys("fork");
  39. else if (pid > 0)
  40. {
  41. close(pipe1[0]);
  42. close(pipe2[1]);
  43. char* s = "Hello there, can you please uppercase this and send it back to me? Thank you!";
  44. write(pipe1[1], s, strlen(s));
  45. close(pipe1[1]);
  46.  
  47. char buff[1024];
  48. bzero(buff, sizeof(buff));
  49. size_t n = read(pipe2[0], buff, sizeof(buff));
  50. pid_t mypid = getpid();
  51. printf("process %ld: got '%s'\n", (long) mypid, buff);
  52. } else
  53. { // Child.
  54. close(pipe1[1]);
  55. close(pipe2[0]);
  56.  
  57. filter(pipe1[0], pipe2[1]);
  58. //filter2(pipe1[0], pipe2[1]); // FIXME: This doesn't work
  59. }
  60. return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement