2013-01-31 61 views
2

我想在ruby进程和Python进程之间进行一些通信;我想使用UNIX套接字。如何使用Unix Socket在ruby和Python之间进行通信

目标: ruby​​进程“fork and exec”Python进程。在ruby进程中,创建一个UNIX套接字对,并将其传递给Python。

Ruby代码(p.rb):

require 'socket' 

r_socket, p_socket = Socket.pair(:UNIX, :DGRAM, 0) 

# I was hoping this file descriptor would be available in the child process 
pid = Process.spawn('python', 'p.py', p_socket.fileno.to_s) 

Process.waitpid(pid) 

Python代码(p.py):

import sys 
import os 
import socket 

# get the file descriptor from command line 
p_fd = int(sys.argv[1]) 

socket.fromfd(p_fd, socket.AF_UNIX, socket.SOCK_DGRAM) 

# f_socket = os.fdopen(p_fd) 
# os.write(p_fd, 'h') 

命令行:

ruby p.rb 

结果:

OSError: [Errno 9] Bad file descriptor 

我希望ruby进程将文件描述符传递给python进程,以便这两个可以使用这些套接字发送数据。

所以,我的问题:

1)是否有可能通过红宝石和如上Python进程之间打开的文件描述符?

2)如果我们可以在两个进程之间传递文件描述符,那么我的代码有什么问题。

回答

5

您已经关闭了,但Ruby spawn默认关闭任何大于2的文件描述符,除非您传递:close_others => false作为参数。请参阅文档:

http://apidock.com/ruby/Kernel/spawn

工作例如:

require 'socket' 

r_socket, p_socket = Socket.pair(:UNIX, :DGRAM, 0) 

pid = Process.spawn('python', 'p.py', p_socket.fileno.to_s, 
        { :close_others => false }) 

# Close the python end (we're not using it on the Ruby side) 
p_socket.close 

# Wait for some data 
puts r_socket.gets 

# Wait for finish 
Process.waitpid(pid) 

的Python:

import sys 
import socket 

p_fd  = int(sys.argv[1]) 
p_socket = socket.fromfd(p_fd, socket.AF_UNIX, socket.SOCK_DGRAM) 

p_socket.send("Hello world\n") 

测试:

> ruby p.rb 
Hello world 
相关问题