rubyでsocketでサーバに接続した後に、(1)forkし、(2)一方のプロセスでsocketをクローズ、(3)他方のプロセスでsocketに対して読み書きを行おうとするとエラーとなります。
同じ理由でOpen3.popen3で存在しないプログラムを実行しようとしてエラーが発生した場合、それまでに接続していたコネクションは切断されてしまいます。
【プログラム】
#!/usr/local/bin/ruby
require 'socket'
def receive(sock)
while true
str = sock.recv(4096)
break if str == ''
print("[#{Process.pid}] #{str}\n")
end
end
sock = TCPSocket.new('localhost', 80)
pid = fork
if pid
# 親プロセス
begin
# 送信
print("[parent] #{Process.pid}\n")
sock.write("GET /nikeda/test/test.cgi HTTP/1.0\n\n")
print("[parent] send\n")
sleep(3)
# 受信
recieve(sock)
rescue
print("[parent] exception\n")
end
else
# 子プロセス
print("[child] end\n")
exit(0)
end
【実行結果】
$ ./test1.rb
[child] end
[parent] 19582
[parent] send
[parent] exception
同じ理由でOpen3.popen3で存在しないプログラムを実行しようとしてエラーが発生した場合、それまでに接続していたコネクションは切断されてしまいます。
【プログラム】
#!/usr/local/bin/ruby
require 'socket'
def receive(sock)
while true
str = sock.recv(4096)
break if str == ''
print("[#{Process.pid}] #{str}\n")
end
end
sock = TCPSocket.new('localhost', 80)
pid = fork
if pid
# 親プロセス
begin
# 送信
print("[parent] #{Process.pid}\n")
sock.write("GET /nikeda/test/test.cgi HTTP/1.0\n\n")
print("[parent] send\n")
sleep(3)
# 受信
recieve(sock)
rescue
print("[parent] exception\n")
end
else
# 子プロセス
print("[child] end\n")
exit(0)
end
【実行結果】
$ ./test1.rb
[child] end
[parent] 19582
[parent] send
[parent] exception