github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/client/lib/fifo/fifo_unix.go (about)

     1  //go:build !windows
     2  // +build !windows
     3  
     4  package fifo
     5  
     6  import (
     7  	"fmt"
     8  	"io"
     9  	"os"
    10  
    11  	"golang.org/x/sys/unix"
    12  )
    13  
    14  // CreateAndRead creates a fifo at the given path, and returns an open function for reading.
    15  // For compatibility with windows, the fifo must not exist already.
    16  //
    17  // It returns a reader open function that may block until a writer opens
    18  // so it's advised to run it in a goroutine different from reader goroutine
    19  func CreateAndRead(path string) (func() (io.ReadCloser, error), error) {
    20  	// create first
    21  	if err := mkfifo(path, 0600); err != nil {
    22  		return nil, fmt.Errorf("error creating fifo %v: %v", path, err)
    23  	}
    24  
    25  	return func() (io.ReadCloser, error) {
    26  		return OpenReader(path)
    27  	}, nil
    28  }
    29  
    30  func OpenReader(path string) (io.ReadCloser, error) {
    31  	return os.OpenFile(path, unix.O_RDONLY, os.ModeNamedPipe)
    32  }
    33  
    34  // OpenWriter opens a fifo file for writer, assuming it already exists, returns io.WriteCloser
    35  func OpenWriter(path string) (io.WriteCloser, error) {
    36  	return os.OpenFile(path, unix.O_WRONLY, os.ModeNamedPipe)
    37  }
    38  
    39  // Remove a fifo that already exists at a given path
    40  func Remove(path string) error {
    41  	return os.Remove(path)
    42  }
    43  
    44  func IsClosedErr(err error) bool {
    45  	err2, ok := err.(*os.PathError)
    46  	if ok {
    47  		return err2.Err == os.ErrClosed
    48  	}
    49  	return false
    50  }
    51  
    52  func mkfifo(path string, mode uint32) (err error) {
    53  	return unix.Mkfifo(path, mode)
    54  }