views:

154

answers:

3

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
A: 

Use net_share.readlines instead of begin/rescue/end.

2nd result for Googling ruby io.popen.

mcandre
I wouldn't do that. It will lead to a dead-lock in an application that waits for input.
Yossi
A: 

try w+ instead of r+

  Mode |  Meaning
  -----+--------------------------------------------------------
  "r"  |  Read-only, starts at beginning of file  (default mode).
  -----+--------------------------------------------------------
  "r+" |  Read-write, starts at beginning of file.
  -----+--------------------------------------------------------
  "w"  |  Write-only, truncates existing file
       |  to zero length or creates a new file for writing.
  -----+--------------------------------------------------------
  "w+" |  Read-write, truncates existing file to zero length
       |  or creates a new file for reading and writing.
  -----+--------------------------------------------------------
  "a"  |  Write-only, starts at end of file if file exists,
       |  otherwise creates a new file for writing.
  -----+--------------------------------------------------------
  "a+" |  Read-write, starts at end of file if file exists,
       |  otherwise creates a new file for reading and
       |  writing.
dutch guy
Hi, I tried w+ (and also a+) but get the same problem, unfortunately.
mackenir
+1  A: 

If you want the net share ... /delete command to always succeed, you can pass the /y flag:

C:\>net share foo /delete /y
Users have open files on foo.  Continuing the operation will force the files closed.

foo was deleted successfully.
psmears
Annoying that the help for net share makes no mention of this option! Thanks.
mackenir