高郎:不能改变孩子的标准



我想完全删除STDIN在父进程和子进程中。

背景:
我正在从主Go进程中生成子进程。它是在Go例程中生成的。fd(本例中为stdin)以某种方式由子进程继承。我的目标是将子进程的stdin设置为nil,以禁止子进程使用任何stdin。

我试着:

os.Stdin = nil
os.Stdin = os.NewFile(uintptr(syscall.Stdin), "/dev/null")

只有"solution"我发现它很脏:

func init() {
go func() {
for {
io.Copy(os.Stdout, os.Stdin)
}
}()
}

有人知道更好的解决方案吗?

更新:
操作系统。Stdin = nil如果Go程序从/dev/tty

读取,将无法工作。我正在生成FFUF

go func() {
tty, err := os.Open("/dev/tty")
if err != nil {
fmt.Println(err)
return
}
defer tty.Close()
inreader := bufio.NewScanner(tty)
inreader.Split(bufio.ScanLines)
started <- true
for inreader.Scan() {
fmt.Printf("handle: " + inreader.Text())
}
}()

我找到了一个解决方案。您需要生成一个没有TTY的进程。为此,必须执行syscallSysProcAttrSetsidSetctty参数。

cmd := exec.Command("echo")
cmd.SysProcAttr = &syscall.SysProcAttr{
Setsid:  true,
Setctty: false,
}
cmd.Start()
cmd.Write([]byte("hello grepngoodbye grep"))
cmd.Close()
cmd.Wait()

最新更新