开发者

Thread-safe external process in ruby, plus checking exitstatus

开发者 https://www.devze.com 2022-12-18 07:33 出处:网络
I want to run a thread-safe piece of script in Ruby that calls an external program, then checks the exit status of that external program. What\'s the best way to do it? So far, I\'ve been checking $?,

I want to run a thread-safe piece of script in Ruby that calls an external program, then checks the exit status of that external program. What's the best way to do it? So far, I've been checking $?, but I think I'm getting a race c开发者_Python百科ondition with other parts of the program.

Here's some example code:

Thread.new do
  `external_program`
  if $?.exitstatus == 0
    # it worked.
  else
    # it didn't work.
  end
end

Ideally, I'd do something like

Process.new(`external_program`).exitstatus

so that the exitstatus was inextricably bound to that process, rather than the last one that happened to complete. Is there any way to do this?


Although rb_last_status (aka $?) is a global variable, Ruby does a magic trick to make it per-thread: In rb_thread_save_context, it stores rb_last_status in the old thread's structure; rb_thread_restore_context sets rb_last_status from the saved value. If you've got a race condition involving $?, it's a Ruby bug.

0

精彩评论

暂无评论...
验证码 换一张
取 消