fifo_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. //go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd
  5. package os_test
  6. import (
  7. "bufio"
  8. "bytes"
  9. "fmt"
  10. "io"
  11. "os"
  12. "path/filepath"
  13. "runtime"
  14. "sync"
  15. "syscall"
  16. "testing"
  17. "time"
  18. )
  19. // Issue 24164.
  20. func TestFifoEOF(t *testing.T) {
  21. switch runtime.GOOS {
  22. case "android":
  23. t.Skip("skipping on Android; mkfifo syscall not available")
  24. }
  25. dir := t.TempDir()
  26. fifoName := filepath.Join(dir, "fifo")
  27. if err := syscall.Mkfifo(fifoName, 0600); err != nil {
  28. t.Fatal(err)
  29. }
  30. var wg sync.WaitGroup
  31. wg.Add(1)
  32. go func() {
  33. defer wg.Done()
  34. w, err := os.OpenFile(fifoName, os.O_WRONLY, 0)
  35. if err != nil {
  36. t.Error(err)
  37. return
  38. }
  39. defer func() {
  40. if err := w.Close(); err != nil {
  41. t.Errorf("error closing writer: %v", err)
  42. }
  43. }()
  44. for i := 0; i < 3; i++ {
  45. time.Sleep(10 * time.Millisecond)
  46. _, err := fmt.Fprintf(w, "line %d\n", i)
  47. if err != nil {
  48. t.Errorf("error writing to fifo: %v", err)
  49. return
  50. }
  51. }
  52. time.Sleep(10 * time.Millisecond)
  53. }()
  54. defer wg.Wait()
  55. r, err := os.Open(fifoName)
  56. if err != nil {
  57. t.Fatal(err)
  58. }
  59. done := make(chan bool)
  60. go func() {
  61. defer close(done)
  62. defer func() {
  63. if err := r.Close(); err != nil {
  64. t.Errorf("error closing reader: %v", err)
  65. }
  66. }()
  67. rbuf := bufio.NewReader(r)
  68. for {
  69. b, err := rbuf.ReadBytes('\n')
  70. if err == io.EOF {
  71. break
  72. }
  73. if err != nil {
  74. t.Error(err)
  75. return
  76. }
  77. t.Logf("%s\n", bytes.TrimSpace(b))
  78. }
  79. }()
  80. select {
  81. case <-done:
  82. // Test succeeded.
  83. case <-time.After(time.Second):
  84. t.Error("timed out waiting for read")
  85. // Close the reader to force the read to complete.
  86. r.Close()
  87. }
  88. }