I wonder whether there's a way to run top -b | grep --line-buffered [some_pid] >> out.log
in Go for a certain amount of time and then kill it after receiving a value from the channel. The os.exec
doesn't seem to support piping in command. Thanks.
Asked
Active
Viewed 1,741 times
1

J Freebird
- 3,664
- 7
- 46
- 81
-
1You can read standard out and use the output there as input to another command. – evanmcdonnal May 19 '16 at 17:31
-
You'll have to do what @evanmcdonnal says. take the output of `top -b` and use it as input for `grep --line-buffered [pid]`; take the output of that and write it to file. – Anfernee May 19 '16 at 17:37
-
2Use `cmd2.Stdin,_ := cmd1.StdoutPipe()` to chain commands, then run them in order. – T. Claverie May 19 '16 at 18:04
-
take a look at [this](http://stackoverflow.com/questions/10781516/how-to-pipe-several-commands-in-go) question – RickyA May 19 '16 at 19:26
1 Answers
1
this is my piping sample, file a calls file b via OS Std Pipe, you can edit this and add timer to do what you need.
// a
package main
import (
"fmt"
"log"
"os/exec"
"runtime"
"time"
)
var cout chan []byte = make(chan []byte)
var cin chan []byte = make(chan []byte)
var exit chan bool = make(chan bool)
func Foo(x byte) byte { return call_port([]byte{1, x}) }
func Bar(y byte) byte { return call_port([]byte{2, y}) }
func Exit() byte { return call_port([]byte{0, 0}) }
func call_port(s []byte) byte {
cout <- s
s = <-cin
return s[1]
}
func start() {
fmt.Println("start")
cmd := exec.Command("../b/b")
stdin, err := cmd.StdinPipe()
if err != nil {
log.Fatal(err)
}
stdout, err2 := cmd.StdoutPipe()
if err2 != nil {
log.Fatal(err2)
}
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
defer stdin.Close()
defer stdout.Close()
for {
select {
case s := <-cout:
stdin.Write(s)
buf := make([]byte, 2)
runtime.Gosched()
time.Sleep(100 * time.Millisecond)
stdout.Read(buf)
cin <- buf
case b := <-exit:
if b {
fmt.Printf("Exit")
return //os.Exit(0)
}
}
}
}
func main() {
go start()
runtime.Gosched()
fmt.Println("30+1=", Foo(30)) //30+1= 31
fmt.Println("2*40=", Bar(40)) //2*40= 80
Exit()
exit <- true
}
file b:
// b
package main
import (
"log"
"os"
)
func foo(x byte) byte { return x + 1 }
func bar(y byte) byte { return y * 2 }
func ReadByte() byte {
b1 := make([]byte, 1)
for {
n, _ := os.Stdin.Read(b1)
if n == 1 {
return b1[0]
}
}
}
func WriteByte(b byte) {
b1 := []byte{b}
for {
n, _ := os.Stdout.Write(b1)
if n == 1 {
return
}
}
}
func main() {
var res byte
for {
fn := ReadByte()
log.Println("fn=", fn)
arg := ReadByte()
log.Println("arg=", arg)
if fn == 1 {
res = foo(arg)
} else if fn == 2 {
res = bar(arg)
} else if fn == 0 {
return //exit
} else {
res = fn //echo
}
WriteByte(1)
WriteByte(res)
}
}