Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/wait.h>
  4. #include <unistd.h>
  5.  
  6. int main()
  7. {
  8. int fds[2];
  9. pid_t pid;
  10.  
  11. /* Create a pipe. File descriptors for the two ends of
  12. the pipe are placed in fds*/
  13. pipe(fds);
  14. /* Fork a child process. */
  15. pid = fork();
  16. if(pid == (pid_t) 0){
  17. /* This is the child process. Close our copy of the
  18. write end of the file descriptor. */
  19. close(fds[1]);
  20. /* Connect the read end of the pipe to standard input. */
  21. dup2(fds[0], STDIN_FILENO);
  22. /* Replace the child process with the "sort" program. */
  23. execlp("sort", "sort", 0);
  24. } else{
  25. /* This is the parent process. */
  26. FILE* stream;
  27. /* Close our copy of the read end of the file descriptor. */
  28. close(fds[0]);
  29. /* Convert the write file descriptor to a FILE object,
  30. and write to it */
  31. stream = fdopen(fds[1], "w");
  32. fprintf(stream, "This is a test.\n");
  33. fprintf(stream, "Hello, world.\n");
  34. fprintf(stream, "This program works.\n");
  35. fflush(stream);
  36. close(fds[1]);
  37. /* Wait for the child process to finish. */
  38. waitpid(pid, NULL, 0);
  39. }
  40. return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement