Front page | perl.beginners |
Postings from March 2002
Trailing nasty files and sockets closing
From:
Bruno Figueira
Date:
March 28, 2002 07:38
Subject:
Trailing nasty files and sockets closing
Message ID:
31E38B53D182D51195FA00508BE3A334A3019E@zwnbc004.cala.nortel.com
People,
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
disconnected?
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.
Regards,
Bruno Figueira
----------- CodeFollows -------
#!/opt/MagellanContrib/bin/perl -w
use Socket;
use IO::Socket;
$SIG{CHLD} = 'IGNORE';
$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()) {
$new_sock->autoflush(1);
$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,
"\n\n";
$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 -----
#!/bin/csh
while ( 1 == 1 )
echo `date` >> myTime
sleep 5
end
-------- reset it mannualy! -----
-
Trailing nasty files and sockets closing
by Bruno Figueira