2018-07-04 19:32:51 +08:00
|
|
|
|
// 多进程通信示例,
|
|
|
|
|
// 子进程每个1秒向父进程发送当前时间,
|
|
|
|
|
// 父进程监听进程消息,收到后打印到终端。
|
2018-05-18 15:45:08 +08:00
|
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"os"
|
|
|
|
|
"fmt"
|
|
|
|
|
"time"
|
|
|
|
|
"gitee.com/johng/gf/g/os/gproc"
|
|
|
|
|
"gitee.com/johng/gf/g/os/gtime"
|
2018-07-04 19:32:51 +08:00
|
|
|
|
"gitee.com/johng/gf/g/os/glog"
|
2018-05-18 15:45:08 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func main () {
|
|
|
|
|
fmt.Printf("%d: I am child? %v\n", gproc.Pid(), gproc.IsChild())
|
|
|
|
|
if gproc.IsChild() {
|
|
|
|
|
gtime.SetInterval(time.Second, func() bool {
|
2018-07-04 19:32:51 +08:00
|
|
|
|
if err := gproc.Send(gproc.PPid(), []byte(gtime.Datetime())); err != nil {
|
|
|
|
|
glog.Error(err)
|
|
|
|
|
}
|
2018-05-18 15:45:08 +08:00
|
|
|
|
return true
|
|
|
|
|
})
|
|
|
|
|
select { }
|
|
|
|
|
} else {
|
|
|
|
|
m := gproc.NewManager()
|
|
|
|
|
p := m.NewProcess(os.Args[0], os.Args, os.Environ())
|
|
|
|
|
p.Start()
|
|
|
|
|
for {
|
|
|
|
|
msg := gproc.Receive()
|
2018-07-04 19:33:22 +08:00
|
|
|
|
fmt.Printf("%d: receive from %d, data: %s\n", gproc.Pid(), msg.Pid, string(msg.Data))
|
2018-05-18 15:45:08 +08:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|