pipe.go 375 B

1234567891011121314151617181920212223
  1. package iox
  2. import "os"
  3. // RedirectInOut redirects stdin to r, stdout to w, and callers need to call restore afterwards.
  4. func RedirectInOut() (restore func(), err error) {
  5. var r, w *os.File
  6. r, w, err = os.Pipe()
  7. if err != nil {
  8. return
  9. }
  10. ow := os.Stdout
  11. os.Stdout = w
  12. or := os.Stdin
  13. os.Stdin = r
  14. restore = func() {
  15. os.Stdin = or
  16. os.Stdout = ow
  17. }
  18. return
  19. }