我怎么能等待文件的写入?(How can I wait for the write of a fil

2019-10-19 07:45发布

当我执行这个程序,它工作得很好,但验证返回false。 如果我重新执行,验证工作。

fullpath是备份的目录, refpath是路径到原始文件:

if (fullpath.include?(refpath) && refpath.empty? == false && fullpath.empty? == false)
  diffpath= "#{fullpath} #{refpath}"
  puts diffpath
  sortie = IO.popen("diff -Bb #{diffpath}").readlines #(fullpath backup_dir)
  #puts fullpath
  if sortie.empty?

    puts "Les fichiers -#{f} sont identiques."

  else
    puts "Modification : [#{refpath}] \n [#{fullpath}] "
  end
end 

主要项目是:

require "modif.rb"
require "testdate.rb"
require "restore_data.rb"

#Pour la sauvegarde des fichiers
puts "__________SAUVEGARDE__________"

#Pour la restauration des fichiers :
puts "__________RESTAURATION__________"

#Vérification de l'intégrité des fichiers restaurés.
puts "__________VERIFICATION__________"
sleep(5.0)
v = Verif.new
v.do_verif(outdir)

当我打开其中还原文件的目录,文件没有完全写入。

调用验证之前,我打电话保存,备份和验证。

sleep不工作。 这个过程是完全暂停,不会写丢失的文件。

Answer 1:

多少千兆字节没有原始文件有多大? 我想,如果sleep 5.0是不是真的有意义,根本原因是别的东西。 还是你使用一个缓慢的USB闪存作为备份目录?

如果你确信你需要等待写入过程中完成的,也许你可以做轮询mtime的备份文件:

finished = false
30.times { # deadline of 30*10 == 300 seconds
  if 5 < (File.mtime(fullpath) - Time.now).abs
    # the backup process had done its job
    finished = true
    break
  end
  sleep 10
}

if finished
  v = Verif.new
...

当备份过程中写入到输出文件的中间, File.mtime(fullpath)应在2秒Time.now小心用2秒计时分辨率FAT文件系统。 我还使用了abs ,因为一些备份程序修改mtime值,因为他们想要的。



Answer 2:

这尚未经过测试,但更多的我怎么会写第一部分:

if ((fullpath != '') && fullpath[refpath] && (refpath != ''))
  sortie = `diff -Bb #{ fullpath } #{ refpath }`
  if sortie == ''
    puts "Les fichiers -#{ f } sont identiques."
  else
    puts "Modification : [#{ refpath }] \n [#{ fullpath }] "
  end
end 

一般来说,你可以简化你的测试。 虽然这是很好的红宝石有empty? 看方法,如果事情有内容,这是比较明显的,如果你用== ''!= ''

使用fullpath[refpath]会返回匹配的字符串或nil ,所以你有一个“truthy / falsey”响应那里,用更少的代码的噪音。

使用反引号或%x让你的“差异”的输出,而不是使用的popenreadlines

在一般情况下,你的代码看起来像你从Java中来。 Ruby有一个非常优雅的语法和写作风格,从而利用它。



文章来源: How can I wait for the write of a file?
标签: ruby file wait