github.com/containerd/containerd@v22.0.0-20200918172823-438c87b8e050+incompatible/cmd/ctr/commands/shim/io_unix.go (about) 1 // +build !windows 2 3 /* 4 Copyright The containerd Authors. 5 6 Licensed under the Apache License, Version 2.0 (the "License"); 7 you may not use this file except in compliance with the License. 8 You may obtain a copy of the License at 9 10 http://www.apache.org/licenses/LICENSE-2.0 11 12 Unless required by applicable law or agreed to in writing, software 13 distributed under the License is distributed on an "AS IS" BASIS, 14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 See the License for the specific language governing permissions and 16 limitations under the License. 17 */ 18 19 package shim 20 21 import ( 22 gocontext "context" 23 "io" 24 "os" 25 "sync" 26 27 "github.com/containerd/fifo" 28 "golang.org/x/sys/unix" 29 ) 30 31 var bufPool = sync.Pool{ 32 New: func() interface{} { 33 buffer := make([]byte, 32<<10) 34 return &buffer 35 }, 36 } 37 38 func prepareStdio(stdin, stdout, stderr string, console bool) (wg *sync.WaitGroup, err error) { 39 wg = &sync.WaitGroup{} 40 ctx := gocontext.Background() 41 42 f, err := fifo.OpenFifo(ctx, stdin, unix.O_WRONLY|unix.O_CREAT|unix.O_NONBLOCK, 0700) 43 if err != nil { 44 return nil, err 45 } 46 defer func(c io.Closer) { 47 if err != nil { 48 c.Close() 49 } 50 }(f) 51 go func(w io.WriteCloser) { 52 p := bufPool.Get().(*[]byte) 53 defer bufPool.Put(p) 54 io.CopyBuffer(w, os.Stdin, *p) 55 w.Close() 56 }(f) 57 58 f, err = fifo.OpenFifo(ctx, stdout, unix.O_RDONLY|unix.O_CREAT|unix.O_NONBLOCK, 0700) 59 if err != nil { 60 return nil, err 61 } 62 defer func(c io.Closer) { 63 if err != nil { 64 c.Close() 65 } 66 }(f) 67 wg.Add(1) 68 go func(r io.ReadCloser) { 69 io.Copy(os.Stdout, r) 70 r.Close() 71 wg.Done() 72 }(f) 73 74 f, err = fifo.OpenFifo(ctx, stderr, unix.O_RDONLY|unix.O_CREAT|unix.O_NONBLOCK, 0700) 75 if err != nil { 76 return nil, err 77 } 78 defer func(c io.Closer) { 79 if err != nil { 80 c.Close() 81 } 82 }(f) 83 if !console { 84 wg.Add(1) 85 go func(r io.ReadCloser) { 86 io.Copy(os.Stderr, r) 87 r.Close() 88 wg.Done() 89 }(f) 90 } 91 92 return wg, nil 93 }