0

I'm looking for a working example how connect standard output of spawned external command to a unix socket. So far, I put up following snippet.

require 'socket'

class XkbSocket
  def initialize
    @sock_cld, @sock_par = UNIXSocket.pair
    at_exit {@sock_cld.close; @sock_par.close}
    pid = spawn 'xkb-switch -W', @sock_cld => @sock_par
    Process.detach pid
  rescue Errno::ENOENT
    @sock_cld.puts "N/A"
  end
end

I am using socket pair, however they are not mapped to some real files so inaccessible for other clients.

I'd like to update above example, so it will create /tmp/mysocket file for external consumers. Thanks.

tadman
  • 208,517
  • 23
  • 234
  • 262
torimus
  • 29
  • 5
  • Are you sure that's the path? It's not specified in your code. – tadman Mar 19 '18 at 19:44
  • I'm sure it is not specified in the snippet. That's why am I asking to add it. Sockets created by `UNIXSocket.pair` have empty path, ie not associated with any file, but I need it for other programs to connect in. – torimus Mar 20 '18 at 00:30
  • That's why you call [`new`](https://ruby-doc.org/stdlib-2.5.0/libdoc/socket/rdoc/UNIXSocket.html) with a path name, not `pair` which does exactly what you say. One program calls `listen`, the other calls `open`. – tadman Mar 20 '18 at 17:45
  • @tadman How can spawned non-ruby process call `open` ? That was the point. `STDOUT` of non-ruby process redirected to a unix socket and a ruby process as a socket client (consumer). – torimus Mar 22 '18 at 13:07
  • You could use tools like [`open3`](https://ruby-doc.org/stdlib-2.5.0/libdoc/open3/rdoc/Open3.html#method-c-popen3) to forward output from one process to a socket you've opened. Don't forget that UNIX sockets that are opened with `new` act a lot like files so you can just redirect output to them using the shell. – tadman Mar 22 '18 at 18:06

0 Answers0