github.com/zxy12/go_duplicate_112_new@v0.0.0-20200807091221-747231827200/src/os/rawconn_test.go (about)

     1  // Copyright 2018 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  // Test use of raw connections.
     6  // +build !plan9,!nacl,!js
     7  
     8  package os_test
     9  
    10  import (
    11  	"os"
    12  	"syscall"
    13  	"testing"
    14  )
    15  
    16  func TestRawConnReadWrite(t *testing.T) {
    17  	t.Parallel()
    18  
    19  	r, w, err := os.Pipe()
    20  	if err != nil {
    21  		t.Fatal(err)
    22  	}
    23  	defer r.Close()
    24  	defer w.Close()
    25  
    26  	rconn, err := r.SyscallConn()
    27  	if err != nil {
    28  		t.Fatal(err)
    29  	}
    30  	wconn, err := w.SyscallConn()
    31  	if err != nil {
    32  		t.Fatal(err)
    33  	}
    34  
    35  	var operr error
    36  	err = wconn.Write(func(s uintptr) bool {
    37  		_, operr = syscall.Write(syscallDescriptor(s), []byte{'b'})
    38  		return operr != syscall.EAGAIN
    39  	})
    40  	if err != nil {
    41  		t.Fatal(err)
    42  	}
    43  	if operr != nil {
    44  		t.Fatal(err)
    45  	}
    46  
    47  	var n int
    48  	buf := make([]byte, 1)
    49  	err = rconn.Read(func(s uintptr) bool {
    50  		n, operr = syscall.Read(syscallDescriptor(s), buf)
    51  		return operr != syscall.EAGAIN
    52  	})
    53  	if err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	if operr != nil {
    57  		t.Fatal(operr)
    58  	}
    59  	if n != 1 {
    60  		t.Errorf("read %d bytes, expected 1", n)
    61  	}
    62  	if buf[0] != 'b' {
    63  		t.Errorf("read %q, expected %q", buf, "b")
    64  	}
    65  }