KUBO Takehiro
1/5/2009 2:27:00 PM
Hi,
On Sun, Jan 4, 2009 at 11:18 PM, Zane Tsang <zengzhenyan@gmail.com> wrote:
> My system is solaris,usually,when i input:"ruby testdb.rb" in the
> terimnate it will print connect db is OK! quickly,but sometimes when it
> print "Begin Conn",the system will wait for several minutes then have
> the follow message:
> env.c:257:in oci8lib.so: ORA-12170: TNS:Connect timeout occurred
> (DBI::DatabaseError)
(snip)
> I have tried to use timeout() function to contorl the time,but it has no
> use.
Timeout.rb doesn't work when it is blocked in a C function.
Ruby-oci8 has non-blocking mode. But it is for established connections.
There is no way when establishing a connection as long as ruby's thread
model is green.
> can you help me?(i want to control the code to excute in 5 secs,when it
> didn't connect to DB in 5 seconds,then it should exit.)
If your platform is UNIX variant, here is a terrible workaround:
kill the process when it cannot connect to the server in 5 seconds.
testdb.rb:
require 'rubygems'
require 'dbi'
notify_target_pid = ARGV[0].to_i
puts "Begin Conn!"
dbh=DBI.connect('DBI:OCI8:orcl','sgpm','sgpm')
puts "connect db is OK!"
Process.kill("HUP", notify_target_pid) # notify that a connection
is established.
dbh.disconnect
timeout.sh:
trap caught_signal=1 1 # trap HUP signal to set caught_signal.
ruby -Ilib -Iext/oci8 testdb.rb $$ & # when a connection is
established, HUP signal is sent.
ruby_process_pid=$!
sleep 5
if test -z "$caught_signal"; then
echo HUP signal has not been caught in 5 seconds.
echo kill the process.
kill -9 $ruby_process_pid
fi
wait $ruby_process_pid