summaryrefslogtreecommitdiff
path: root/software/vendor/go.bug.st/serial/unixutils/pipe.go
blob: 748de34e30b8d9858f15e93e0ef8d0cf7faf199d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//
// Copyright 2014-2023 Cristian Maglie. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//

//go:build linux || darwin || freebsd || openbsd

package unixutils

import (
	"fmt"
	"syscall"
)

// Pipe represents a unix-pipe
type Pipe struct {
	opened bool
	rd     int
	wr     int
}

// Open creates a new pipe
func (p *Pipe) Open() error {
	fds := []int{0, 0}
	if err := syscall.Pipe(fds); err != nil {
		return err
	}
	p.rd = fds[0]
	p.wr = fds[1]
	p.opened = true
	return nil
}

// ReadFD returns the file handle for the read side of the pipe.
func (p *Pipe) ReadFD() int {
	if !p.opened {
		return -1
	}
	return p.rd
}

// WriteFD returns the flie handle for the write side of the pipe.
func (p *Pipe) WriteFD() int {
	if !p.opened {
		return -1
	}
	return p.wr
}

// Write to the pipe the content of data. Returns the numbre of bytes written.
func (p *Pipe) Write(data []byte) (int, error) {
	if !p.opened {
		return 0, fmt.Errorf("Pipe not opened")
	}
	return syscall.Write(p.wr, data)
}

// Read from the pipe into the data array. Returns the number of bytes read.
func (p *Pipe) Read(data []byte) (int, error) {
	if !p.opened {
		return 0, fmt.Errorf("Pipe not opened")
	}
	return syscall.Read(p.rd, data)
}

// Close the pipe
func (p *Pipe) Close() error {
	if !p.opened {
		return fmt.Errorf("Pipe not opened")
	}
	err1 := syscall.Close(p.rd)
	err2 := syscall.Close(p.wr)
	p.opened = false
	if err1 != nil {
		return err1
	}
	if err2 != nil {
		return err2
	}
	return nil
}