1// Copyright 2021 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 dragonfly || freebsd || linux || netbsd || openbsd || solaris
6// +build dragonfly freebsd linux netbsd openbsd solaris
7
8package unix_test
9
10import (
11	"testing"
12
13	"golang.org/x/sys/unix"
14)
15
16func TestPipe2(t *testing.T) {
17	const s = "hello"
18	var pipes [2]int
19	err := unix.Pipe2(pipes[:], 0)
20	if err != nil {
21		t.Fatalf("pipe2: %v", err)
22	}
23	r := pipes[0]
24	w := pipes[1]
25	go func() {
26		n, err := unix.Write(w, []byte(s))
27		if err != nil {
28			t.Errorf("bad write: %v", err)
29			return
30		}
31		if n != len(s) {
32			t.Errorf("bad write count: %d", n)
33			return
34		}
35		err = unix.Close(w)
36		if err != nil {
37			t.Errorf("bad close: %v", err)
38			return
39		}
40	}()
41	var buf [10 + len(s)]byte
42	n, err := unix.Read(r, buf[:])
43	if err != nil {
44		t.Fatalf("bad read: %v", err)
45	}
46	if n != len(s) {
47		t.Fatalf("bad read count: %d", n)
48	}
49	if string(buf[:n]) != s {
50		t.Fatalf("bad contents: %s", string(buf[:n]))
51	}
52	err = unix.Close(r)
53	if err != nil {
54		t.Fatalf("bad close: %v", err)
55	}
56}
57
58func checkNonblocking(t *testing.T, fd int, name string) {
59	t.Helper()
60	flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFL, 0)
61	if err != nil {
62		t.Errorf("fcntl(%s, F_GETFL) failed: %v", name, err)
63	} else if flags&unix.O_NONBLOCK == 0 {
64		t.Errorf("O_NONBLOCK not set in %s flags %#x", name, flags)
65	}
66}
67
68func checkCloseonexec(t *testing.T, fd int, name string) {
69	t.Helper()
70	flags, err := unix.FcntlInt(uintptr(fd), unix.F_GETFD, 0)
71	if err != nil {
72		t.Errorf("fcntl(%s, F_GETFD) failed: %v", name, err)
73	} else if flags&unix.FD_CLOEXEC == 0 {
74		t.Errorf("FD_CLOEXEC not set in %s flags %#x", name, flags)
75	}
76}
77
78func TestNonblockingPipe2(t *testing.T) {
79	var pipes [2]int
80	err := unix.Pipe2(pipes[:], unix.O_NONBLOCK|unix.O_CLOEXEC)
81	if err != nil {
82		t.Fatalf("pipe2: %v", err)
83	}
84	r := pipes[0]
85	w := pipes[1]
86	defer func() {
87		unix.Close(r)
88		unix.Close(w)
89	}()
90
91	checkNonblocking(t, r, "reader")
92	checkCloseonexec(t, r, "reader")
93	checkNonblocking(t, w, "writer")
94	checkCloseonexec(t, w, "writer")
95}
96