Go衍生(Spawn)新进程

itfanr · 2015-01-23 22:00:01 · 2474 次点击 · 预计阅读时间 1 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2015-01-23 22:00:01 的文章,其中的信息可能已经有所发展或是发生改变。

package mainimport "fmt"import "io/ioutil"import "os/exec"func main() {
    dateCmd := exec.Command("date")
    dateOut, err := dateCmd.Output()    if err != nil {        panic(err)
    }
    fmt.Println("> date")
    fmt.Println(string(dateOut))

    grepCmd := exec.Command("grep", "hello")
    grepIn, _ := grepCmd.StdinPipe()
    grepOut, _ := grepCmd.StdoutPipe()
    grepCmd.Start()
    grepIn.Write([]byte("hello grep\ngoodbye grep"))
    grepIn.Close()
    grepBytes, _ := ioutil.ReadAll(grepOut)
    grepCmd.Wait()
    fmt.Println("> grep hello")
    fmt.Println(string(grepBytes))

    lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
    lsOut, err := lsCmd.Output()    if err != nil {        panic(err)
    }
    fmt.Println("> ls -a -l -h")
    fmt.Println(string(lsOut))
}

执行结果:

> date
2015年 1月23日 星期五 21时29分39秒 CST

> grep hello
hello grep

> ls -a -l -h
total 32
drwxr-xr-x   6 itfanr  admin   204B  1 23 21:29 .
drwxrwxrwx   6 itfanr  admin   204B 12 27 09:52 ..
-rw-rw-r--@  1 itfanr  admin   721B  1 23 21:29 excute.go
drwxr-xr-x  13 itfanr  admin   442B  1 22 21:06 github.com

参考:

  1. https://gobyexample.com/spawning-processes

  2. http://tobegit3hub1.gitbooks.io/understanding-linux-processes/content/go_example/spawn.html

3. https://github.com/mmcgrana/gobyexample



有疑问加站长微信联系(非本文作者)

本文来自:开源中国博客

感谢作者:itfanr

查看原文:Go衍生(Spawn)新进程

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2474 次点击  
加入收藏 微博
1 回复  |  直到 2000-01-01 00:00:00
qkb_75_go
qkb_75_go · #1 · 10年之前

刚看到题目, 我还以为 Go 终于像 Erlang 一样支持 spawn 操作了, 好真的有点小激动呢; 细看了一下代码,不是这个意思。
既然要用 go ,应该发挥 go 的优势:
为什么不 ls 一个 goroutine, grep 一个 goroutine ,两者用 chan string 沟通一下, 这样 可以遍历打印出所有的路径呢?

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传