Sha256: a92509b5a7a212fa9a23411770ecd626afca0902465392e8992dd297166a883f

Contents?: true

Size: 1.7 KB

Versions: 109

Compression:

Stored size: 1.7 KB

Contents

require "open3"

module J1
  module Utils
    module Exec2
      extend self

      # Runs a program in a sub-shell and return a Process::Status on exit
      #
      # title - prepend a title on all messages
      # *args - a list of strings containing the program name and arguments
      #
      def run(title, *args)
        Open3.popen3(*args) do |stdin, stdout, stderr, status|

          # manage software interrupt on Ctrl-C
          trap('INT') {
            timestamp = Time.now.strftime("%Y-%m-%d %H:%M:%S")
            puts "#{timestamp} - #{title}: Received Ctrl-C to stop"
            [stdin, stdout, stderr].each(&:close)
            raise SystemExit
          }

          # manage messages on stdout
          stdout_thr = Thread.new do
            # exit the tread silently
            Thread.current.report_on_exception = false
            stdout.each_line do |line|
              timestamp = Time.now.strftime("%Y-%m-%d %H:%M:%S")
              puts "#{timestamp} - #{title}: #{line}"
            end
          end

          # manage messages on stdout
          stderr_thr = Thread.new do
            # exit the tread silently
            Thread.current.report_on_exception = false
            stderr.each_line do |line|
              timestamp = Time.now.strftime("%Y-%m-%d %H:%M:%S")
              puts "#{timestamp} - " + "\e[31m" + "#{title}: #{line}" + "\e[0m"
            end
          end

          # combine channels stdout, stderr for output
          [stdout_thr, stderr_thr].each(&:join)

          # close channels explicitly to exit gracefully
          [stdin, stdout, stderr].each(&:close)

          # exit and return Process::Status
          status.value
        end
      end

    end
  end
end

Version data entries

109 entries across 109 versions & 1 rubygems

Version Path
j1-template-2024.3.19 lib/j1/utils/exec2.rb
j1-template-2024.3.18 lib/j1/utils/exec2.rb
j1-template-2024.3.17 lib/j1/utils/exec2.rb
j1-template-2024.3.16 lib/j1/utils/exec2.rb
j1-template-2024.3.15 lib/j1/utils/exec2.rb
j1-template-2024.3.14 lib/j1/utils/exec2.rb
j1-template-2024.3.13 lib/j1/utils/exec2.rb
j1-template-2024.3.12 lib/j1/utils/exec2.rb
j1-template-2024.2.1 lib/j1/utils/exec2.rb
j1-template-2024.2.0 lib/j1/utils/exec2.rb
j1-template-2024.1.5 lib/j1/utils/exec2.rb
j1-template-2024.1.4 lib/j1/utils/exec2.rb
j1-template-2024.1.3 lib/j1/utils/exec2.rb
j1-template-2024.1.2 lib/j1/utils/exec2.rb
j1-template-2024.1.1 lib/j1/utils/exec2.rb
j1-template-2024.1.0 lib/j1/utils/exec2.rb
j1-template-2024.0.3 lib/j1/utils/exec2.rb
j1-template-2024.0.2 lib/j1/utils/exec2.rb
j1-template-2024.0.1 lib/j1/utils/exec2.rb
j1-template-2024.0.0 lib/j1/utils/exec2.rb