You should start by checking the return value of
print - it will return false eventually when it tries to flush an output buffer and the socket it's writing to is closed. You may also want to set
$| so that output is sent immediately and closure is detected immediately.
-- Chip Salzenberg, Free-Floating Agent of Chaos