RunUnixShell 运行UnixShell,支持context
(options *structs.ShellOptions)
| 65 | |
| 66 | // RunUnixShell 运行UnixShell,支持context |
| 67 | func RunUnixShell(options *structs.ShellOptions) (*structs.ShellResult, error) { |
| 68 | fpath, err := exec.LookPath(options.Name) |
| 69 | if err != nil { |
| 70 | return nil, err |
| 71 | } |
| 72 | result := structs.ShellResult{} |
| 73 | proc := exec.Command(fpath, options.Args...) |
| 74 | proc.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // 把编译器整个放置在进程组里 |
| 75 | |
| 76 | var stderr, stdout bytes.Buffer |
| 77 | |
| 78 | if options.StdWriter != nil && options.StdWriter.Output != nil { |
| 79 | proc.Stdout = options.StdWriter.Output |
| 80 | } else { |
| 81 | proc.Stdout = &stdout |
| 82 | } |
| 83 | if options.StdWriter != nil && options.StdWriter.Error != nil { |
| 84 | proc.Stderr = options.StdWriter.Error |
| 85 | } else { |
| 86 | proc.Stderr = &stderr |
| 87 | } |
| 88 | |
| 89 | if options.StdWriter != nil && options.StdWriter.Input != nil { |
| 90 | proc.Stdin = options.StdWriter.Input |
| 91 | } else { |
| 92 | stdin, err := proc.StdinPipe() |
| 93 | if err != nil { |
| 94 | return nil, err |
| 95 | } |
| 96 | if options.OnStart != nil { |
| 97 | err = options.OnStart(stdin) |
| 98 | if err != nil { |
| 99 | return nil, err |
| 100 | } |
| 101 | } |
| 102 | _ = stdin.Close() |
| 103 | } |
| 104 | |
| 105 | // 监听是否超时 |
| 106 | go func() { |
| 107 | select { |
| 108 | case <-options.Context.Done(): |
| 109 | // 干掉进程组 |
| 110 | // CommandContext自带的功能没有考虑到这个操作: |
| 111 | _ = syscall.Kill(-proc.Process.Pid, syscall.SIGKILL) |
| 112 | } |
| 113 | }() |
| 114 | |
| 115 | if err = proc.Start(); err != nil { |
| 116 | return nil, err |
| 117 | } |
| 118 | |
| 119 | err = proc.Wait() |
| 120 | |
| 121 | if options.StdWriter == nil || options.StdWriter.Output == nil { |
| 122 | result.Stdout = stdout.String() |
| 123 | } |
| 124 | if options.StdWriter == nil || options.StdWriter.Error == nil { |
no test coverage detected