github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/cmds/exp/rush/tty_linux.go (about)

     1  // Copyright 2012-2017 the u-root 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  package main
     6  
     7  import (
     8  	"fmt"
     9  	"log"
    10  	"os"
    11  	"os/signal"
    12  	"unsafe"
    13  
    14  	"golang.org/x/sys/unix"
    15  )
    16  
    17  var (
    18  	ttypgrp int
    19  	ttyf    *os.File
    20  )
    21  
    22  // tty does whatever needs to be done to set up a tty for GOOS.
    23  func tty() {
    24  	var err error
    25  
    26  	sigs := make(chan os.Signal, 512)
    27  	signal.Notify(sigs, os.Interrupt)
    28  	signal.Ignore(unix.SIGTTOU)
    29  	go func() {
    30  		for i := range sigs {
    31  			fmt.Println(i)
    32  		}
    33  	}()
    34  
    35  	// N.B. We can continue to use this file, in the foreground function,
    36  	// but the runtime closes it on exec for us.
    37  	ttyf, err = os.OpenFile("/dev/tty", os.O_RDWR, 0)
    38  	if err != nil {
    39  		log.Printf("rush: Can't open a console; no job control in this session")
    40  		return
    41  	}
    42  	// Get the current pgrp, and the pgrp on the tty.
    43  	// get current pgrp
    44  	ttypgrp, err = unix.IoctlGetInt(int(ttyf.Fd()), unix.TIOCGPGRP)
    45  	if err != nil {
    46  		log.Printf("Can't get foreground: %v", err)
    47  		ttyf.Close()
    48  		ttyf = nil
    49  		ttypgrp = 0
    50  	}
    51  }
    52  
    53  func foreground() {
    54  	// Place process group in foreground.
    55  	if ttypgrp != 0 {
    56  		_, _, errno := unix.RawSyscall(unix.SYS_IOCTL, ttyf.Fd(), uintptr(unix.TIOCSPGRP), uintptr(unsafe.Pointer(&ttypgrp)))
    57  		if errno != 0 {
    58  			log.Printf("rush pid %v: Can't set foreground to %v: %v", os.Getpid(), ttypgrp, errno)
    59  		}
    60  	}
    61  
    62  }