gpt4 book ai didi

ruby - nohup 下奇怪的 Ruby 输出滞后?

转载 作者:太空狗 更新时间:2023-10-29 12:18:07 29 4
gpt4 key购买 nike

nohup 下运行时,我发现 Ruby 脚本有一些令人困惑的行为。基本上我是这样做的:

require 'logger'

logger_file = open('/mnt/dbsdata/output.log', File::WRONLY | File::APPEND | File::CREAT)
LOGGER = Logger.new(logger_file)
LOGGER.level = Logger::INFO

def run_command(cmd,display=true)
if display
LOGGER.info "Executing: #{cmd}"
end
output = `#{cmd} 2>&1` ; results=$?.success?
if ! results
LOGGER.error "FAILED to execute #{cmd}"
LOGGER.error output
return false
end
return true
end

begin
run_command("some_longrunning_command", true)
run_command("some_other_longrunning_command",true)
# etc...
end

这里奇怪的是,无论是像上面那样使用 Logger 还是普通 puts 到 STDOUT (nohup.out),输出时间都偏离了。我想我可以跟踪日志文件并查看实时日志消息(日志消息、执行命令、重复),但是发生的是大量消息刷新以一次性记录许多陈旧消息,在他们的命令执行很久之后已经执行并完成。

从 shell 中执行脚本时:

`nohup ruby myscript.rb &`

当不在 nohup 下运行时,它的行为符合预期。

有没有人遇到过这种情况并且知道好的解决方法?

最佳答案

我不能肯定地说,但这听起来像是一个 IO sync 问题。 I/O 通常被缓冲以提高速度。 RAM 比磁盘快很多,所以读取和写入都是临时存储的,直到代码请求数据,或者磁盘能够接收它。 Ruby 的 IO 类具有 sync= 方法,可让您告诉 Ruby 在写入时立即刷新缓冲区。

这应该有效:

logger_file = open('/mnt/dbsdata/output.log', File::WRONLY | File::APPEND | File::CREAT)
logger_file.sync = true
LOGGER = Logger.new(logger_file)
LOGGER.level = Logger::INFO

为简单起见,您可以使用以下方法为输出创建正确的模式:

    logger_file = File.open('/mnt/dbsdata/output.log', 'a')

关于ruby - nohup 下奇怪的 Ruby 输出滞后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19455667/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com