《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.2 KiB

  1. /*
  2. * From
  3. * [url]http://www.crasseux.com/books/ctutorial/Programming-with-pipes.html[/url]
  4. * but changed to use fgets() instead of the GNU extension getdelim()
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. int main()
  10. {
  11. FILE *ps_pipe;
  12. FILE *grep_pipe;
  13. int bytes_read;
  14. char buffer[100]; /* could be anything you want */
  15. /* Open our two pipes
  16. ls -a | grep pipe*
  17. */
  18. ps_pipe = popen("/bin/ls -a", "r");
  19. grep_pipe = popen("/bin/grep 'pipe*'", "w");
  20. /* Check that pipes are non-null, therefore open */
  21. if ((!ps_pipe) || (!grep_pipe)) {
  22. fprintf(stderr, "One or both pipes failed.\n");
  23. return EXIT_FAILURE;
  24. }
  25. bytes_read = 0;
  26. while (fgets(buffer, sizeof(buffer), ps_pipe)) {
  27. fprintf(grep_pipe, "%s", buffer);
  28. bytes_read += strlen(buffer);
  29. }
  30. printf("Total bytes read = %d\n", bytes_read);
  31. /* Close ps_pipe, checking for errors */
  32. if (pclose(ps_pipe) != 0) {
  33. fprintf(stderr, "Could not run 'ls', or other error.\n");
  34. }
  35. /* Close grep_pipe, cehcking for errors */
  36. if (pclose(grep_pipe) != 0) {
  37. fprintf(stderr, "Could not run 'grep', or other error.\n");
  38. }
  39. /* Exit! */
  40. return 0;
  41. }