github.com/c9s/go@v0.0.0-20180120015821-984e81f64e0c/src/os/signal/internal/pty/pty.go (about)

     1  // Copyright 2017 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  // +build darwin dragonfly freebsd linux,!android netbsd openbsd
     6  // +build cgo
     7  
     8  // Package pty is a simple pseudo-terminal package for Unix systems,
     9  // implemented by calling C functions via cgo.
    10  // This is only used for testing the os/signal package.
    11  package pty
    12  
    13  /*
    14  #define _XOPEN_SOURCE 600
    15  #include <fcntl.h>
    16  #include <stdlib.h>
    17  #include <unistd.h>
    18  */
    19  import "C"
    20  
    21  import (
    22  	"fmt"
    23  	"os"
    24  )
    25  
    26  // Open returns a master pty and the name of the linked slave tty.
    27  func Open() (master *os.File, slave string, err error) {
    28  	m, err := C.posix_openpt(C.O_RDWR)
    29  	if err != nil {
    30  		return nil, "", fmt.Errorf("posix_openpt: %v", err)
    31  	}
    32  	if _, err := C.grantpt(m); err != nil {
    33  		C.close(m)
    34  		return nil, "", fmt.Errorf("grantpt: %v", err)
    35  	}
    36  	if _, err := C.unlockpt(m); err != nil {
    37  		C.close(m)
    38  		return nil, "", fmt.Errorf("unlockpt: %v", err)
    39  	}
    40  	slave = C.GoString(C.ptsname(m))
    41  	return os.NewFile(uintptr(m), "pty-master"), slave, nil
    42  }