develooper Front page | perl.beginners | Postings from March 2002

Trailing nasty files and sockets closing

Bruno Figueira
March 28, 2002 07:38
Trailing nasty files and sockets closing
Message ID:

I am working in a script I would call file2port. The idea is to trail (like
tail -f) a file and send it to a TCP port. For every TCP connection incoming
to my server, I would trail a file and print its new lines to the client
peer. However, I am having two problems I would like to present:

1. I can't tell exactly when the client disconnected. I expected to check
for any variable that could tell me the status of that connection but I
could not find it. So I am using a "Broken Pipe" signal to discover this,
but it is not quite elegant. Question: how can I tell the client has

2. I am trailing a file (e.g. myTime). The trailing would be ok if the file
is not periodically overwritten by another application. I mean, from time to
time, another program cleans the file (the size goes to zero bytes) and
starts writing on it again. It seems that perl looses the tracking of it and
it takes to much time (and to many lines lost) to re-synch with the file
again. Question: How do I improve the trailing so that I wont miss lines
when the file is rewritten?

I have copied the code in this e-mail, since it's quite small.


Bruno Figueira

----------- CodeFollows -------
#!/opt/MagellanContrib/bin/perl -w
use Socket;
use IO::Socket;

$sock = new IO::Socket::INET (LocalHost => 'localhost',
                              LocalPort => 1200,
                                  Proto => 'tcp',
                                 Listen => 5,
                                  Reuse => 1
die "Socket could not be created. Reason: $!" unless $sock;

while ($new_sock = $sock->accept()) {
    $pid = fork();
    die "Cannot fork: $!" unless defined($pid);

    if ($pid == 0) {
       $thisHost = $new_sock->peerhost();
       $thisPort = $new_sock->peerport();
       print "New connection from ", $thisHost, ", port ", $thisPort,
       $SIG{PIPE} = 'IGNORE';
       open(HORAS, "< myTime")
           or die "Couldn't open myTime for reading: $!\n";
       while (<HORAS>) {  }
       for (;;) {
          seek(HORAS, 0, 1);
          $status = print $new_sock <HORAS>;
          if ( !$status ) { last; }
          sleep 1;
       print "Connection Finished! ", "Host: ", $thisHost, ", port ",
$thisPort, "\n\n";
       close (HORAS);
       exit(0); # Child process exits when it is done.
    } # else this is the parent process, which goes back to accept()

close ($sock);

-------- An easy way to create the myTime file -----
while ( 1 == 1 )
echo `date` >> myTime
sleep 5

-------- reset it mannualy! ----- Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About