# Asynchronous copies

**URL:** <https://www.ruby-forum.com/t/asynchronous-copies/166549>\
**Category:** Rails\
**Created:** [April 27, 2009, 9:05am UTC](https://www.ruby-forum.com/t/asynchronous-copies/166549 "2009-04-27T09:05:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pdenize](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a88e4f/32.png) [@pdenize](https://www.ruby-forum.com/u/pdenize)\
**Post date:** [April 27, 2009, 9:05am UTC](https://www.ruby-forum.com/t/asynchronous-copies/166549/1 "2009-04-27T09:05:07Z")

</div>

I have managed to get copies working well between Windows and Linux  
but I noticed that the libraries allow Asynchronous operation. I can  
send Async commands and the loop till they complete but copies seem to  
stay busy forever. Maybe I am just not cleaning up right (it does not  
seem so)

ssh\_session = Net::SSH.start(…etc…)

# ssh\_session.exec(“sleep 10”)

ssh\_session.sftp.connect.upload(src\_file, tgt\_file)

ssh\_session.loop(1) {  
puts “I=#{interrupted} B=”+@ssh\_session.busy?.inspect  
not interrupted and @ssh\_session.busy?  
}

If the sleep is called (instead of the upload) it waits 10 secs and  
then is not busy and wakes.  
But the copy will not wake. Since I have hundreds of files to copy  
I’d like to set them all off, do some other work, and then wait for  
them to complete (rather than wait for them one at a time with  
upload!) and then do the other work.

Any help would be appreciated… should I cleanup the “sftp.connect”?  
How? When (if it is asynchronous)?

Thanks

---

<div class="post-metadata">

**Author:** ![pdenize](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/a88e4f/32.png) [@pdenize](https://www.ruby-forum.com/u/pdenize)\
**Post date:** [April 28, 2009, 3:19am UTC](https://www.ruby-forum.com/t/asynchronous-copies/166549/2 "2009-04-28T03:19:06Z")

</div>

Found the solution

ssh\_session = Net::SSH.start(…etc…)

sftp\_conn = ssh\_session.sftp.connect! # needed to block connect here  
(!) or the upload seems to hang  
sftp\_conn.upload(src\_file, tgt\_file)

interrupted = false  
trap(‘INT’) { interrupted = true }  
sftp\_conn.loop() {  
not interrupted and sftp\_conn.pending\_requests.any? # check for  
pending requests  
}  
sftp\_conn.close\_channel()  
ssh\_session.loop(1) {  
not interrupted and ssh\_session.busy?  
}  
sftp\_conn = ssh\_session.sftp.connect!

One word of warning if sending lots of files (\>300) fast then you may  
run out of open file handles (Windows).  
I avoid the error by doing this call each now and then when starting  
another upload

if (sftp\_conn.pending\_requests.length\>=100)  
interrupted = false  
trap(‘INT’) { interrupted = true }  
sftp\_conn.loop() {  
not interrupted and sftp\_conn.pending\_requests.any?  
}  
end

I guess I could have exited when the queue was smaller not empty also.

Hope this helps someone else.
