...

Source file src/os/fifo_test.go

Documentation: os

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

View as plain text