{"id":4156,"date":"2018-11-02T20:51:37","date_gmt":"2018-11-02T12:51:37","guid":{"rendered":"https:\/\/ixyzero.com\/blog\/?p=4156"},"modified":"2018-11-02T20:51:37","modified_gmt":"2018-11-02T12:51:37","slug":"go%e8%af%ad%e8%a8%80%e5%ad%a6%e4%b9%a013-%e5%80%9f%e5%8a%a9exec%e6%89%a7%e8%a1%8c%e5%a4%96%e9%83%a8%e5%91%bd%e4%bb%a4","status":"publish","type":"post","link":"https:\/\/ixyzero.com\/blog\/archives\/4156.html","title":{"rendered":"Go\u8bed\u8a00\u5b66\u4e60#13-\u501f\u52a9exec\u6267\u884c\u5916\u90e8\u547d\u4ee4"},"content":{"rendered":"<p>=Start=<\/p>\n<h4 id=\"id-\u6a21\u677f-\u7f18\u7531\uff1a\">\u7f18\u7531\uff1a<\/h4>\n<p>\u5728\u5b9e\u9645\u7f16\u7a0b\u8fc7\u7a0b\u4e2d\uff0c\u4e0d\u8bba\u662f\u5e95\u5c42\u7684C\u8bed\u8a00\u8fd8\u662f\u4e0a\u5c42\u7684Java\/Python\uff0c\u5728\u5b9e\u73b0\u67d0\u4e9b\u529f\u80fd\u7684\u65f6\u5019\uff0c\u5c11\u4e0d\u4e86\u8c03\u7528\u5916\u90e8\u547d\u4ee4\u3002\u6240\u4ee5\u8fd9\u91cc\u6574\u7406\u603b\u7ed3\u4e00\u4e0b\u5728Go \u8bed\u8a00\u4e2d\u501f\u52a9os\/exec\u5305\u6267\u884c\u5916\u90e8\u547d\u4ee4\u7684\u65b9\u6cd5\uff0c\u4ee5\u53ca\u4e00\u4e2a\u5b9e\u73b0\u4e86\u8d85\u65f6\u9000\u51fa\u529f\u80fd\u7684\u547d\u4ee4\u6267\u884c\u51fd\u6570\u3002<\/p>\n<h4 id=\"id-\u6a21\u677f-\u6b63\u6587\uff1a\">\u6b63\u6587\uff1a<\/h4>\n<h5 id=\"id-\u6a21\u677f-\u53c2\u8003\u89e3\u7b54\uff1a\">\u53c2\u8003\u89e3\u7b54\uff1a<\/h5>\n<p><span style=\"color: #ff0000;\"><strong>Go \u8bed\u8a00\u4e2d\u4f7f\u7528 exec.Cmd \u7ed3\u6784\u7c7b\u578b\u6765\u62bd\u8c61\u7528\u6237\u8981\u6267\u884c\u7684\u5916\u90e8\u547d\u4ee4\uff1b<\/strong><\/span><strong>\u8be5\u7c7b\u578b\u4e0b\u7684 Command \u65b9\u6cd5\uff0c\u63a5\u6536\u7ed9\u5b9a\u53c2\u6570\u5e76\u8fd4\u56de Cmd \u7ed3\u6784\u4f53\uff0c\u4f46\u5b83\u53ea\u8bbe\u7f6e\u8fd4\u56deCmd\u7ed3\u6784\u4e2d\u7684Path\u548cArgs\u3002<\/strong><\/p>\n<pre class=\"lang:default decode:true \">func Command(name string, arg ...string) *Cmd\r\n\r\ntype Cmd struct {\r\n    Path string\r\n\r\n    Args []string\r\n\r\n    Env []string\r\n    Dir string\r\n\r\n    Stdin io.Reader\r\n    Stdout io.Writer\r\n    Stderr io.Writer\r\n\r\n    \/\/ ExtraFiles specifies additional open files to be inherited by the\r\n    \/\/ new process. It does not include standard input, standard output, or\r\n    \/\/ standard error. If non-nil, entry i becomes file descriptor 3+i.\r\n    ExtraFiles []*os.File\r\n\r\n    \/\/ SysProcAttr holds optional, operating system-specific attributes.\r\n    \/\/ Run passes it to os.StartProcess as the os.ProcAttr's Sys field.\r\n    SysProcAttr *syscall.SysProcAttr\r\n\r\n    \/\/ Process is the underlying process, once started.\r\n    Process *os.Process\r\n\r\n    \/\/ ProcessState contains information about an exited process,\r\n    \/\/ available after a call to Wait or Run.\r\n    ProcessState *os.ProcessState\r\n    \/\/ contains filtered or unexported fields\r\n}<\/pre>\n<p>\u5982\u679c\u540d\u79f0 name \u4e2d\u4e0d\u5305\u542b\u8def\u5f84\u5206\u9694\u7b26\uff0c\u547d\u4ee4\u5c06\u4f7f\u7528LookPath\u51fd\u6570\u5c06\u540d\u79f0\u89e3\u6790\u4e3a\u5b8c\u6574\u8def\u5f84\u3002\u5426\u5219\uff0c\u5b83\u76f4\u63a5\u4f7f\u7528\u540d\u79f0\u4f5c\u4e3a\u8def\u5f84\u3002<span style=\"color: #ff0000;\"><strong>LookPath\u51fd\u6570\u7528\u4e8e\u5728PATH\u73af\u5883\u53d8\u91cf\u6307\u5b9a\u7684\u76ee\u5f55\u4e2d\u641c\u7d22\u4e00\u4e2a\u540d\u4e3afile\u7684\u53ef\u6267\u884c\u4e8c\u8fdb\u5236\u6587\u4ef6\u3002\u5982\u679c\u6587\u4ef6\u5305\u542b\u659c\u6760\uff0c\u5219\u76f4\u63a5\u5c1d\u8bd5\u4f7f\u7528\u8be5\u6587\u4ef6\uff0c\u5e76\u4e14\u4e0d\u67e5\u770b\u8def\u5f84\u3002\u67e5\u8be2\u7ed3\u679c\u53ef\u80fd\u662f\u7edd\u5bf9\u8def\u5f84\u6216\u76f8\u5bf9\u4e8e\u5f53\u524d\u76ee\u5f55\u7684\u76f8\u5bf9\u8def\u5f84\u3002<\/strong><\/span><\/p>\n<p>\u8fd4\u56de\u7684Cmd\u4e2d\u7684Args\u5b57\u6bb5\u7531 \u547d\u4ee4\u540dname \u8ddf\u7740 \u53c2\u6570arg \u4e00\u8d77\u7ec4\u6210\uff0c\u56e0\u6b64 arg \u672c\u8eab\u4e0d\u5e94\u8be5\u5305\u542b\u547d\u4ee4\u540d\u3002\u4f8b\u5982\uff0c\u547d\u4ee4(&#8220;echo&#8221;,&#8221;hello&#8221;)\u3002Args[0]\u59cb\u7ec8\u662f\u540d\u79f0\uff0c\u800c\u4e0d\u662f\u53ef\u80fd\u89e3\u6790\u7684\u8def\u5f84\u3002<\/p>\n<hr \/>\n<p>\u4e0b\u9762\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u793a\u4f8b\uff08\u5305\u542b <code>tr<\/code>\u00a0\u547d\u4ee4\u548c <code>echo<\/code>\u00a0\u547d\u4ee4\u7684\u8c03\u7528\uff0c\u8fd8\u6709\u5bf9LookPath\u51fd\u6570\u7684\u6d4b\u8bd5\uff09\uff1a<\/p>\n<pre class=\"lang:default decode:true \">package main\r\n\r\nimport (\r\n    \"bytes\"\r\n    \"fmt\"\r\n    \"log\"\r\n    \"os\/exec\"\r\n    \"strings\"\r\n)\r\n\r\nfunc main() {\r\n    cmd := exec.Command(\"tr\", \"a-z\", \"A-Z\")\r\n    cmd.Stdin = strings.NewReader(\"some input\")\r\n    var out bytes.Buffer\r\n    cmd.Stdout = &amp;out\r\n    err := cmd.Run()\r\n    if err != nil {\r\n        log.Fatal(err)\r\n    }\r\n    fmt.Printf(\"in all caps: %q\\n\", out.String())\r\n\r\n    \/\/ log.Fatal() is equivalent to fmt.Print() followed by a call to os.Exit(1).\r\n\r\n    \/\/ cmd = exec.Command(\"sleep\", \"5\") \/\/ need 5 seconds to finish\r\n    cmd = exec.Command(\"echo\", \"hello\") \/\/ finish immediately\r\n    err = cmd.Start()\r\n    if err != nil {\r\n        log.Fatal(err)\r\n    }\r\n    log.Printf(\"Waiting for command to finish...\")\r\n    err = cmd.Wait()\r\n    log.Printf(\"Command finished with error: %v\", err)\r\n\r\n    path, err := exec.LookPath(\"\/bin\/w\")\r\n    if err != nil {\r\n        log.Println(\"installing `\/bin\/w` is in your future\")\r\n    } else {\r\n        fmt.Printf(\"`\/bin\/w` is available at %q\\n\", path)\r\n    }\r\n\r\n    path, err = exec.LookPath(\"bin\/w\")\r\n    if err != nil {\r\n        log.Println(\"installing `bin\/w` is in your future\")\r\n    } else {\r\n        fmt.Printf(\"`bin\/w` is available at %q\\n\", path)\r\n    }\r\n\r\n    path, err = exec.LookPath(\"w\")\r\n    if err != nil {\r\n        log.Println(\"installing w is in your future\")\r\n    } else {\r\n        fmt.Printf(\"`w` is available at %q\\n\", path)\r\n    }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>\u4f46\u662f\u5728\u5b9e\u9645\u73af\u5883\u4e2d\uff0c\u5404\u79cd\u5404\u6837\u7684\u60c5\u51b5\u90fd\u6709\u53ef\u80fd\u51fa\u73b0\uff0c\u6bd4\u5982\u4e00\u4e2a\u672c\u5730\u4ee5\u53ca\u6d4b\u8bd5\u73af\u5883\u4e2d\u6267\u884c\u53ea\u9700\u89811\u30012\u79d2\u7684\u547d\u4ee4\u6216\u811a\u672c\u5230\u4e86\u7ebf\u4e0a\u53ef\u80fd10\u79d2\u949f\u4e5f\u6267\u884c\u4e0d\u5b8c\uff0c\u4f46\u662f\uff0c\u6211\u4eec\u7684\u6d41\u7a0b\u53c8\u4e0d\u80fd\u4e00\u76f4\u5361\u5728\u8fd9\u91cc\u7b49\u5f85\u5b8c\u6210\uff0c\u9700\u8981\u6709\u4e00\u4e2a\u8d85\u65f6\u9000\u51fa\u7684\u673a\u5236\u3002\u8fd9\u65f6\u5c31\u53ef\u4ee5\u53c2\u8003\u4e0b\u9762\u7684\u793a\u4f8b\uff1a<\/p>\n<pre class=\"lang:default decode:true \">package main\r\n\r\nimport (\r\n    \"bytes\"\r\n    \"fmt\"\r\n    \"log\"\r\n    \"os\/exec\"\r\n    \"strings\"\r\n    \"syscall\"\r\n    \"time\"\r\n)\r\n\r\n\/\/ https:\/\/linkscue.com\/2018\/06\/03\/2018-06-03-golang-exec-command-timeout-trace\/\r\n\r\n\/\/ \u5220\u9664\u8f93\u51fa\u5185\u5bb9\u4e2d\u7684\\x00\u548c\u591a\u4f59\u7684\u7a7a\u683c\r\nfunc trimOutput(buffer bytes.Buffer) string {\r\n    return strings.TrimSpace(string(bytes.TrimRight(buffer.Bytes(), \"\\x00\")))\r\n}\r\n\r\n\/\/ \u5b9e\u65f6\u6253\u5370\u8f93\u51fa\uff08\u5229\u7528Ticker\u6bcf\u9694\u4e00\u79d2\u4eceout\u7f13\u51b2\u533a\u4e2d\u53d6\u51fa\u4e00\u90e8\u5206\u5185\u5bb9\u8fdb\u884c\u6253\u5370\uff09\r\nfunc traceOutput(out *bytes.Buffer) {\r\n    offset := 0\r\n    t := time.NewTicker(time.Second)\r\n    defer t.Stop()\r\n    for {\r\n        &lt;-t.C\r\n        result := bytes.TrimRight((*out).Bytes(), \"\\x00\") \/\/ \u6bcf\u6b21\u8bfb\u53d6\u7684\u662f\u6240\u6709\u7684\u8f93\u51fa\u5185\u5bb9\r\n        size := len(result)\r\n        rows := bytes.Split(bytes.TrimSpace(result), []byte{'\\n'})\r\n        nRows := len(rows)\r\n        newRows := rows[offset:nRows]\r\n        if result[size-1] != '\\n' {\r\n            newRows = rows[offset : nRows-1]\r\n        }\r\n        if len(newRows) &lt; offset { \/\/ \u5224\u65ad\u662f\u5426\u6ee1\u8db3\u6253\u5370\u6761\u4ef6\uff08\u4e4b\u524d\u662f\u5426\u5df2\u6253\u5370\u8fc7\uff09\r\n            continue\r\n        }\r\n        for _, row := range newRows {\r\n            \/\/ log.Println(string(row)) \/\/ \u4f1a\u5728\u6bcf\u884c\u65e5\u5fd7\u5f00\u5934\u6dfb\u52a0\u65e5\u671f\u65f6\u95f4\u4fe1\u606f\r\n            fmt.Println(string(row))\r\n        }\r\n        offset += len(newRows) \/\/ offset\u8bb0\u5f55\u7684\u662f\u5df2\u6253\u5370\u884c\u6570\u7684\u504f\u79fb\u503c\r\n    }\r\n}\r\n\r\n\/\/ \u8fd0\u884cShell\u547d\u4ee4\uff0c\u8bbe\u5b9a\u8d85\u65f6\u65f6\u95f4\uff08\u79d2\uff09\r\nfunc ExecCmdWithTimeout(timeout int, cmd string, args ...string) (stdout, stderr string, e error) {\r\n    if len(cmd) == 0 {\r\n        e = fmt.Errorf(\"cannot run a empty command\")\r\n        return\r\n    }\r\n    var out, err bytes.Buffer\r\n    command := exec.Command(cmd, args...) \/\/ \u6839\u636e\u8f93\u5165\u7684\u53c2\u6570\u751f\u6210 Cmd \u7c7b\u578b\u7684\u7ed3\u6784\u4f53\r\n    command.Stdout = &amp;out\r\n    command.Stderr = &amp;err\r\n    command.Start() \/\/ \u5f00\u59cb\u6267\u884c\u547d\u4ee4\r\n    \/\/ \u4e0b\u97622\u884c\u7528\u4e8e\u542f\u52a8\u4e00\u4e2a\u5355\u72ec\u7684goroutine\u7b49\u5f85\u547d\u4ee4\u6267\u884c\u7ed3\u675f\r\n    done := make(chan error) \/\/ \u521b\u5efa\u4e00\u4e2a channel \u7528\u4e8e\u627f\u8f7d\u547d\u4ee4\u6267\u884c\u72b6\u6001\u7684\u901a\u8baf\r\n    go func() { done &lt;- command.Wait() }()\r\n    \/\/ \u542f\u52a8routine\u6301\u7eed\u6253\u5370\u8f93\u51fa\uff08\u9700\u8981\u65f6\u518d\u6253\u5f00\uff0c\u4e0d\u9700\u8981\u5b9e\u65f6\u6253\u5370\u7684\u8bdd\u53ef\u4ee5\u5728\u6700\u540e\u4e00\u6b21\u6027\u6253\u5370\u51fa\u6765\uff09\r\n    \/\/ go traceOutput(&amp;out)\r\n    \/\/ \u8bbe\u5b9a\u8d85\u65f6\u65f6\u95f4\uff0c\u5e76select\u5b83\r\n    after := time.After(time.Duration(timeout) * time.Second) \/\/ \u53ef\u4ee5\u7406\u89e3\u4e3a\u542f\u52a8\u4e00\u4e2a\u5b9a\u65f6\u5668\r\n    select {\r\n    case &lt;-after: \/\/ \u5f53\u5230\u4e86\u8bbe\u5b9a\u7684\u8d85\u65f6\u65f6\u95f4\u540e\uff0c\u8fdb\u5165\u8fd9\u4e2a case \u8bed\u53e5\r\n        command.Process.Signal(syscall.SIGINT) \/\/ \u5148\u53d1\u9001SIGINT\u518d\u53bbkill\u6389\u547d\u4ee4\uff0c\u4ee5\u786e\u4fdd\u547d\u4ee4\u7684\u8f93\u51fa\u5b8c\u6574\r\n        time.Sleep(time.Second)                \/\/ \u7b49\u5f851\u79d2\u540e\u518d\u53bbkill\r\n        command.Process.Kill()\r\n        \/\/ if err2 := command.Process.Kill(); err2 != nil { \/\/ \"os: process already finished\"\r\n        \/\/     log.Printf(\"failed to kill: %s, error: %q\\n\", command.Path, err2)\r\n        \/\/ }\r\n        go func() {\r\n            &lt;-done \/\/ \u5f53\u4e3b\u52a8kill\u8fdb\u7a0b\u65f6\uff0c\u5176\u5b9e\u5c31\u4e0d\u592a\u5173\u5fc3done\u4e2d\u7684\u7ed3\u679c\u4e86\uff0c\u6240\u4ee5\u4e3b\u52a8\u6d88\u8d39\uff0c\u4e14\u7528go\u4ee5\u907f\u514d\u8fd9\u91cc\u5361\u4f4f\r\n        }()\r\n        log.Printf(\"\u8fd0\u884c\u547d\u4ee4\uff08%s\uff09\u8d85\u65f6\uff0c\u8d85\u65f6\u8bbe\u5b9a\uff1a%v \u79d2\u3002\",\r\n            fmt.Sprintf(`%s %s`, cmd, strings.Join(args, \" \")), timeout)\r\n    case &lt;-done: \/\/ \u4ece channel \u4e2d\u53d6\u51fa\u547d\u4ee4\u7684\u6267\u884c\u72b6\u6001\u5e76\u5b58\u5165\u53d8\u91cf e \u4e2d\r\n    }\r\n    stdout = trimOutput(out)\r\n    stderr = trimOutput(err)\r\n    return\r\n}\r\n\r\nfunc main() {\r\n    \/\/ _, _, e := ExecCmdWithTimeout(5, \"ping\", \"114.114.114.114\")\r\n    stdout, stderr, e := ExecCmdWithTimeout(5, \"ping\", \"114.114.114.114\")\r\n    log.Println(\"stdout:\\n\", stdout)\r\n    log.Println(\"stderr:\\n\", stderr)\r\n    log.Println(\"error:\\n\", e)\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<h5 id=\"id-\u6a21\u677f-\u53c2\u8003\u94fe\u63a5\uff1a\">\u53c2\u8003\u94fe\u63a5\uff1a<\/h5>\n<ul>\n<li><a href=\"https:\/\/linkscue.com\/2018\/06\/03\/2018-06-03-golang-exec-command-timeout-trace\/\">GO\u8bed\u8a00\u6267\u884c\u547d\u4ee4\u8d85\u65f6\u7684\u8bbe\u7f6e<\/a>#<strong>nice<\/strong><\/li>\n<li><a href=\"http:\/\/ulricqin.com\/post\/set-script-timeout-use-golang\/\">\u4f7f\u7528Golang\u4e3a\u811a\u672c\u6267\u884c\u8bbe\u7f6e\u8d85\u65f6\u65f6\u95f4<\/a><\/li>\n<li><a href=\"https:\/\/medium.com\/@vCabbage\/go-timeout-commands-with-os-exec-commandcontext-ba0c861ed738\">Go: Timeout Commands with os\/exec CommandContext<\/a><br \/>\n<a href=\"https:\/\/www.cnblogs.com\/shhnwangjian\/p\/9039742.html\">https:\/\/www.cnblogs.com\/shhnwangjian\/p\/9039742.html<\/a><\/li>\n<li><a href=\"https:\/\/stackoverflow.com\/questions\/11886531\/terminating-a-process-started-with-os-exec-in-golang\">Go \u8bed\u8a00\u4e2d\u5982\u4f55\u7ec8\u6b62\u4e00\u4e2a\u7528os\/exec\u542f\u52a8\u7684\u8fdb\u7a0b<\/a><\/li>\n<\/ul>\n<p>=END=<\/p>\n","protected":false},"excerpt":{"rendered":"<p>=Start= \u7f18\u7531\uff1a \u5728\u5b9e\u9645\u7f16\u7a0b\u8fc7\u7a0b\u4e2d\uff0c\u4e0d\u8bba\u662f\u5e95\u5c42\u7684C\u8bed\u8a00\u8fd8\u662f\u4e0a\u5c42\u7684Java\/Python\uff0c\u5728\u5b9e\u73b0\u67d0\u4e9b\u529f\u80fd\u7684 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[23,7],"tags":[564,1249,1248,517],"class_list":["post-4156","post","type-post","status-publish","format-standard","hentry","category-knowledgebase-2","category-programing","tag-golang","tag-lookpath","tag-os-exec","tag-timeout"],"views":4726,"_links":{"self":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/4156","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/comments?post=4156"}],"version-history":[{"count":1,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/4156\/revisions"}],"predecessor-version":[{"id":4160,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/4156\/revisions\/4160"}],"wp:attachment":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/media?parent=4156"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/categories?post=4156"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/tags?post=4156"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}