Signal problems on win32

I have a simple program that reads from a socket, compresses the data
and writes it to a file. Because I'm using zlib, I must intercept
SIGINT so I can close the GzipWriter before exiting or the file will
be corrupted. Problem is, sometimes my handler gets called, and
sometimes it doesn't. When it doesn't, the program just hangs and I
have to kill the process from task manager.

This is with ruby 1.8.2 (2004-07-29) [i386-mswin32] on Windows XP. If
I perform some additional manipulation of the data before compressing
it (as shown in the commented lines in the loop), the problem occurs
much more frequently.

I really want to use ruby for this task, but this problem is a
showstopper. Are there any workarounds I might try?

require 'socket'
require 'zlib'

sock = UDPSocket.open
sock.bind('', 6161)

f = File.new('junk.gz', 'wb')
outFile = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)

trap('INT') { puts 'exiting'; outFile.close; exit 0 }

interval = 5
channelId = 1

loop {
  packet = sock.recv(8192)
  outFile << packet
  #outFile << [sprintf('%08i', interval), channelId, sprintf('%05i',
  #packet.size), packet].pack('a8 c a5 a*') << "\n"
  puts "got #{packet.size} bytes"
}

I've encountered this as well, and had just resorted to using
mechanisms other than SIGINT to terminate the program. However, there's
a workaround suggested in the ruby-talk archives:

http://blade.nagaokaut.ac.jp/ruby/ruby-talk/82924

Basically, it amounts to putting a busy-wait loop in a background
thread; it seems that adding the thread changes Ruby's signal handling
and allows the SIGINT to get delivered correctly.

Anyone have a more satisfactory explanation for the source of the
problem?

···

--
Lennon
rcoder.net

Hi,

At Fri, 22 Oct 2004 06:14:15 +0900,
rcoder wrote in [ruby-talk:117320]:

I've encountered this as well, and had just resorted to using
mechanisms other than SIGINT to terminate the program. However, there's
a workaround suggested in the ruby-talk archives:

http://blade.nagaokaut.ac.jp/ruby/ruby-talk/82924

        * win32/win32.c (rb_w32_call_handler): workaround for Ctrl-C.

···

Wed Sep 22 13:02:02 2004 NAKAMURA Usaku <usa@ruby-lang.org>

--
Nobu Nakada