新手问题 关于 popen - 的问题,求助好心人啊

p0p3 · 2013年09月10日 · 最后由 p0p3 回复于 2013年09月11日 · 3181 次阅读

pipe = IO.popen("-","w+") if pipe pipe.puts "Get a job!" $stderr.puts "Child says '#{pipe.gets.chomp}'" else $stderr.puts "Dad says '#{gets.chomp}'" puts "OK" end

输出: Dad says 'Get a job!' Child says 'OK'

子进程和父进程的输出互换了,好心人帮忙解释下产生这种情况具体的实现过程是怎样的啊

nil 是子进程 你写反了

If a block is given with a cmd of “-”, the block will be run in two separate processes: once in the parent, and once in a child. The parent process will be passed the pipe object as a parameter to the block, the child version of the block will be passed nil, and the child’s standard in and standard out will be connected to the parent through the pipe. Not available on all platforms.

#1 楼 @ChanceDoor 没有写反啊

回 LZ,就是子进程的 STDIN 和 STDOUT 连接到了父进程的 pipe 上。

#2 楼 @kenshin54 the child version of the block will be passed nil 那他的 if pipe 不是应该是父进程么?

那为何子进程的输出变成了父进程的输入的啊,请教下具体的过程@ChanceDoor

#4 楼 @p0p3 popen 方法以一个子进程来运行一个命令,并且把这个进程的标准输入和标准输出绑定到 Ruby 的 IO 对象。向 IO 对象写数据,子进程就可以从它的标准输入读取数据,而子进程输出的数据,也可以通过 Ruby 的 IO 对象读出来。

来源:http://my4java.itpub.net/post/9983/65277

#3 楼 @ChanceDoor 是啊,父进程说“我的子进程说了 OK”,子进程说”我的父进程说了 Get a job!“

#6 楼 @kenshin54 $stderr.puts 不会输出到子进程吧 pipe.puts 才是输出到子进程 对不?

#7 楼 @ChanceDoor 嗯 只有 stdin 和 stdout 会,stderr 不会,文档是这么说的。

#8 楼 @kenshin54 哦 那是对的 结果也是对的 以为求助都是代码错了呢

@kenshin54 就是子进程的 STDIN 和 STDOUT 连接到了父进程的 pipe 上。 这个我知道,我的意思是为啥父进程的输入又成了子进程的输出

#10 楼 @p0p3 父进程没有直接输入啊,他用的是 pipe 对象的啊

呵呵,谢谢啊

需要 登录 后方可回复, 如果你还没有账号请 注册新账号