How to use IO.popen to write-to and read-from a child process?
Posted
by mackenir
on Stack Overflow
See other posts from Stack Overflow
or by mackenir
Published on 2010-05-25T09:41:04Z
Indexed on
2010/05/25
10:01 UTC
Read the original article
Hit count: 251
I am running net share
from a ruby script to delete a windows network share.
If files on the share are in use, net share
will ask the user if they want to go ahead with the deletion, so my script needs to inspect the output from the command, and write out Y
if it detects that net share
is asking it for input.
In order to be able to write out to the process I open it with access flags "r+"
.
When attempting to write to the process with IO#puts
, I get an error:
Errno::EPIPE: Broken pipe
What am I doing wrong here? (The error occurs on the line net_share.puts "Y"
)
(The question text written out by net share
is not followed by a newline, so I am using IO#readpartial
to read in the output.)
def delete_network_share share_path
command = "net share #{share_path} /DELETE"
net_share = IO.popen(command, "r+")
text = ""
while true
begin
line = net_share.readpartial 1000 #read all the input that's available
rescue EOFError
break
end
text += line
if text.scan("Do you want to continue this operation? (Y/N)").size > 0
net_share.puts "Y"
net_share.flush #probably not needed?
end
end
net_share.close
end
© Stack Overflow or respective owner