pipe.scm 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. ; Copyright (c) 1993-2007 by Richard Kelsey and Jonathan Rees. See file COPYING.
  2. ; Scheme analogues of Posix popen() and pclose() library calls.
  3. ; Create a pipe and exec COMMAND to talk to one end of the pipe while
  4. ; PROC is handed the other end. If INPUT? is true PROC gets the input
  5. ; end of the pipe and COMMAND gets the output end.
  6. (define (call-with-mumble-pipe input?)
  7. (lambda (command proc)
  8. (call-with-values open-pipe
  9. (lambda (input-pipe output-pipe)
  10. (let ((pid (fork)))
  11. (if pid
  12. ; Parent
  13. (let ((proc-port (if input? input-pipe output-pipe)))
  14. (close-port (if input? output-pipe input-pipe))
  15. (call-with-values
  16. (lambda ()
  17. (proc proc-port))
  18. (lambda vals
  19. (close-port proc-port)
  20. (wait-for-child-process pid)
  21. (apply values vals))))
  22. ; Child
  23. (dynamic-wind
  24. (lambda ()
  25. #f)
  26. (lambda ()
  27. (if input?
  28. (remap-file-descriptors! (current-input-port)
  29. output-pipe
  30. (current-error-port))
  31. (remap-file-descriptors! input-pipe
  32. (current-output-port)
  33. (current-error-port)))
  34. (exec-file "/bin/sh" "-c" command))
  35. (lambda ()
  36. (exit 1)))))))))
  37. (define (close-port port)
  38. (if (input-port? port)
  39. (close-input-port port)
  40. (close-output-port port)))
  41. (define call-with-input-pipe
  42. (call-with-mumble-pipe #t))
  43. (define call-with-output-pipe
  44. (call-with-mumble-pipe #f))