Last active
August 29, 2015 14:24
-
-
Save OneOfOne/c1ddb1b0292423770aad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"os" | |
"os/exec" | |
"strings" | |
"time" | |
) | |
const script = ` | |
(function(){ | |
var fs = require('fs'), | |
system = require('system'); | |
console.log('hi from phantomjs'); | |
console.log(JSON.stringify(system.os)); | |
var s = fs.open('/dev/fd/3', 'r'), | |
line; | |
while(line = s.readLine()) { // this blocks forever until fd3 is closed. | |
console.log('phantomjs: ', line); | |
} | |
s.close(); | |
phantom.exit(); | |
})(); | |
` | |
func main() { | |
cp := "phantomjs" | |
if len(os.Args) > 1 { | |
if os.Args[1] == "/dev/stdin" { | |
mainChild() | |
return | |
} | |
cp = os.Args[0] | |
} | |
cmd := exec.Command(cp, "/dev/stdin") | |
cmd.Stdin = strings.NewReader(script) | |
rp, wp, err := os.Pipe() | |
if err != nil { | |
return | |
} | |
defer rp.Close() | |
cmd.ExtraFiles = []*os.File{rp} | |
cmd.Stdout = os.Stdout | |
cmd.Stderr = os.Stderr | |
if err = cmd.Start(); err != nil { | |
return | |
} | |
rp.Close() | |
wp.WriteString("test 1\n") | |
wp.WriteString("test 2\n") | |
wp.WriteString("test 3\n") | |
time.AfterFunc(1*time.Second, func() { | |
fmt.Println("---timing out---") | |
wp.Close() | |
}) | |
cmd.Wait() | |
} | |
func mainChild() { | |
f := os.NewFile(3, "fd3") | |
buf := bufio.NewReader(f) | |
fmt.Println("hi from go") | |
for { | |
line, err := buf.ReadString('\n') | |
if err != nil { | |
break | |
} | |
fmt.Println("go:", strings.TrimSpace(line)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment