[23246] in Perl-Users-Digest
Perl-Users Digest, Issue: 5467 Volume: 10
daemon@ATHENA.MIT.EDU (Perl-Users Digest)
Tue Sep 9 00:05:49 2003
Date: Mon, 8 Sep 2003 21:05:06 -0700 (PDT)
From: Perl-Users Digest <Perl-Users-Request@ruby.OCE.ORST.EDU>
To: Perl-Users@ruby.OCE.ORST.EDU (Perl-Users Digest)
Perl-Users Digest Mon, 8 Sep 2003 Volume: 10 Number: 5467
Today's topics:
Re: Active Perl, Windows scheduler, regular task... (Chas Friedman)
Re: Can Perl do this? <tim@vegeta.ath.cx>
Re: Can Perl do this? <postmaster@castleamber.com>
Re: Creating special DATE format <REMOVEsdnCAPS@comcast.net>
Re: Flocking Advise <postmaster@castleamber.com>
Re: Flocking Advise (David Efflandt)
multiple arrays from one text file with one column (Faz)
Re: multiple arrays from one text file with one column <bwalton@rochester.rr.com>
Re: multiple arrays from one text file with one column <postmaster@castleamber.com>
Re: Perl Arguements <kkeller-usenet@wombat.san-francisco.ca.us>
Re: Perl Arguements (Sam Holden)
Re: Perl Arguements <postmaster@castleamber.com>
Re: Problem with simple contact script. (Tom)
Re: Problem with simple contact script. <postmaster@castleamber.com>
Re: Quotes and circular references <bwalton@rochester.rr.com>
Threads troubles <spaceman-a299c-20030925@ausgehaucht.sensenmann.at>
Re: Threads troubles (Sam Holden)
Re: <bwalton@rochester.rr.com>
Digest Administrivia (Last modified: 6 Apr 01) (Perl-Users-Digest Admin)
----------------------------------------------------------------------
Date: Tue, 9 Sep 2003 03:40:43 +0000 (UTC)
From: friedman@math.utexas.edu (Chas Friedman)
Subject: Re: Active Perl, Windows scheduler, regular task...
Message-Id: <bjji3r$mkq$1@geraldo.cc.utexas.edu>
Alan J. Flavell wrote:
..............
>Thanks! - so I've defined the windows scheduler task to be
>
> wperl c:\path\to\script.pl
..............
Is there some documentation for "wperl" somewhere? I can't seem to find
anything about it, and always wondered just what it did...
Thanks!
chas
------------------------------
Date: 8 Sep 2003 18:34:55 -0700
From: Tim Hammerquist <tim@vegeta.ath.cx>
Subject: Re: Can Perl do this?
Message-Id: <slrnblqbh6.acj.tim@vegeta.ath.cx>
John Bokma graced us by uttering:
> CountryLover wrote:
<snip>
> > Is this something that Perl could be persuaded to do?
>
> Yes, quite easy. I do similar things often with Perl :-)
>
> Probably a *nix hacker could do most, if not all with GNU tools
> like find (the txt files), head (to get the first 25), mv,
> grep/sed, mkdir, mv and such. Probably in a one-liner.
Yes, it's possible with standard Unix tools. But as it will most
likely be extended and expanded, I'd recommend Perl anyway. :)
Tim Hammerquist
--
Every man is guilty of all the good he didn't do.
-- Voltaire
------------------------------
Date: Tue, 09 Sep 2003 04:35:38 +0200
From: John Bokma <postmaster@castleamber.com>
Subject: Re: Can Perl do this?
Message-Id: <1063075043.818123@halkan.kabelfoon.nl>
Tim Hammerquist wrote:
> John Bokma graced us by uttering:
>
>>CountryLover wrote:
>
> <snip>
>
>>>Is this something that Perl could be persuaded to do?
>>
>>Yes, quite easy. I do similar things often with Perl :-)
>>
>>Probably a *nix hacker could do most, if not all with GNU tools
>>like find (the txt files), head (to get the first 25), mv,
>>grep/sed, mkdir, mv and such. Probably in a one-liner.
>
> Yes, it's possible with standard Unix tools. But as it will most
> likely be extended and expanded, I'd recommend Perl anyway. :)
Indeed. I use Perl to forgot all the horrible experiences with sed, awk
and friends :-)
--
Kind regards, feel free to mail: mail(at)johnbokma.com (or reply)
virtual home: http://johnbokma.com/ ICQ: 218175426
John web site hints: http://johnbokma.com/websitedesign/
------------------------------
Date: Mon, 08 Sep 2003 21:14:56 -0500
From: "Eric J. Roode" <REMOVEsdnCAPS@comcast.net>
Subject: Re: Creating special DATE format
Message-Id: <Xns93F0E28041A27sdn.comcast@206.127.4.25>
-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1
"\"Dandy\" Randy" <ducott@hotmail.com> wrote in
news:L387b.116217$la.2582463@news1.calgary.shaw.ca:
> Hello peoples,
>
> I could use some help writing a script that will create and print the
> date in a special format. Here is what I am looking to accomplish:
>
> When my main script is executed:
>
> assign the date to a variable in this format = month/day/year all in
> two digit format like so: 09/08/03
use Time::Format;
my $date_var = $time{'mm/dd/yy'};
- --
Eric
$_ = reverse sort $ /. r , qw p ekca lre uJ reh
ts p , map $ _. $ " , qw e p h tona e and print
-----BEGIN xxx SIGNATURE-----
Version: PGPfreeware 7.0.3 for non-commercial use <http://www.pgp.com>
iQA/AwUBP1032WPeouIeTNHoEQIr9QCghCzirwQHBLmEHd/zlcjAsOwm9XsAoPVg
5ho/qdFn2pUZiOnKBHV95Do1
=00Ye
-----END PGP SIGNATURE-----
------------------------------
Date: Tue, 09 Sep 2003 03:06:57 +0200
From: John Bokma <postmaster@castleamber.com>
Subject: Re: Flocking Advise
Message-Id: <1063069722.409051@halkan.kabelfoon.nl>
"Dandy" Randy wrote:
> Hey ... could use some advise on the best file locking method ... at present
> I use the following:
>
> #!/usr/bin/perl
>
> use strict;
> use 5.004;
> use Fcntl qw(:DEFAULT :flock);
>
> open (FH, "<data.txt") or die "Can't open file: $!";
> flock (FH, LOCK_EX) or die "Can't lock file: $!";
> $data=<FH>;
> chomp ($data);
> ($total,$opened,$followed)=split(/\|/,$data);
> close(FH);
>
> $opened = $opened + 1;
BEEP *RED ALERT* RACE CONDITION DETECTED....
suppose the script is called in between opens the file and writes the
new counter value and then....
> sysopen(FH, "data.txt", O_WRONLY | O_CREAT) or die "can't open filename:
> $!";
> flock (FH, LOCK_EX) or die "can't lock filename: $!";
> truncate (FH, 0) or die "can't truncate filename: $!";
> print FH "$total|$opened|$followed\n";
> close FH;
hell breaks lose since you just overwrote the counter....
eg:
a -> reads 5
b -> reads 5
b -> increments
b -> writes 6
a -> increments
a -> writes 6
On a busy site there could be a, b, c etc.
> What I see going on here is the code opens a file that does not contain
> critical data, thus protecting the real data, and the user cannot open the
> real file until the sem lock becomes free ... Two questions ... is this a
> good approach, and secondly ... whats inside the sem file? is it an empty
> dummy file? does it have to have a .sem extension? Thank you for you
> opinions.
The lock on your file is *the* semaphore. No need for a separate lock file.
--
Kind regards, feel free to mail: mail(at)johnbokma.com (or reply)
virtual home: http://johnbokma.com/ ICQ: 218175426
John web site hints: http://johnbokma.com/websitedesign/
------------------------------
Date: Tue, 9 Sep 2003 03:16:07 +0000 (UTC)
From: efflandt@xnet.com (David Efflandt)
Subject: Re: Flocking Advise
Message-Id: <slrnblqhfn.5cs.efflandt@typhoon.xnet.com>
On Tue, 09 Sep 2003 01:03:25 GMT, \"Dandy\" Randy <ducott@hotmail.com> wrote:
> Hey ... could use some advise on the best file locking method ... at present
> I use the following:
>
> #!/usr/bin/perl
>
> use strict;
> use 5.004;
> use Fcntl qw(:DEFAULT :flock);
>
> open (FH, "<data.txt") or die "Can't open file: $!";
> flock (FH, LOCK_EX) or die "Can't lock file: $!";
> $data=<FH>;
> chomp ($data);
> ($total,$opened,$followed)=split(/\|/,$data);
> close(FH);
>
> $opened = $opened + 1;
>
> sysopen(FH, "data.txt", O_WRONLY | O_CREAT) or die "can't open filename:
> $!";
> flock (FH, LOCK_EX) or die "can't lock filename: $!";
> truncate (FH, 0) or die "can't truncate filename: $!";
> print FH "$total|$opened|$followed\n";
> close FH;
>
> print "Content-type: text/html \n\n";
> print "Done\n";
> exit;
>
> It seems to work ok, but am not sure if it is a good approach or not. One of
> my main questions is ... what about sememorph locks ... been reading in
> different places that you start you file open code by opening a dummy
> sememorph file ... kinda like this:
One problem with what you are doing (hit counter?) is, what happens if
multiple instances of the script run at the same time? One script reads
it, closes it, another script opens it and reads it, first script opens
and writes to it, and second script modifies stale data and saves it.
My approach is to open it read/write ( +< ), flock it, seek the beginning
(just in case something else opened it before flock), modify and save
data, and then close it. Then another instance would have to wait until
flock cleared before it was able to flock, read and modify fresh data.
Otherwise your count could easily end up short.
--
David Efflandt - All spam ignored http://www.de-srv.com/
http://www.autox.chicago.il.us/ http://www.berniesfloral.net/
http://cgi-help.virtualave.net/ http://hammer.prohosting.com/~cgi-wiz/
------------------------------
Date: 8 Sep 2003 19:29:31 -0700
From: lfazal@hotmail.com (Faz)
Subject: multiple arrays from one text file with one column
Message-Id: <13ddbd75.0309081829.1a6803cc@posting.google.com>
Hello
I have a text file in a single column which has name address, phone
age of each people as below
Name
Address
phone
age
Name
Address
phone
age
I want to put all the names in the names array, all the address in
address array all the phone in the phone array etc
Please help
Thanks
------------------------------
Date: Tue, 09 Sep 2003 02:38:28 GMT
From: Bob Walton <bwalton@rochester.rr.com>
Subject: Re: multiple arrays from one text file with one column
Message-Id: <3F5D3C67.9010804@rochester.rr.com>
Faz wrote:
...
> I have a text file in a single column which has name address, phone
> age of each people as below
>
> Name
> Address
> phone
> age
> Name
> Address
> phone
> age
>
> I want to put all the names in the names array, all the address in
> address array all the phone in the phone array etc
...
An excellent starting point is with the book "Learning Perl". Read
that, and if you then have problems you can't get past, please post here
again.
--
Bob Walton
------------------------------
Date: Tue, 09 Sep 2003 04:56:09 +0200
From: John Bokma <postmaster@castleamber.com>
Subject: Re: multiple arrays from one text file with one column
Message-Id: <1063076274.766676@halkan.kabelfoon.nl>
Faz wrote:
> Hello
>
> I have a text file in a single column which has name address, phone
> age of each people as below
>
> Name
> Address
> phone
> age
> Name
> Address
> phone
> age
So all people are called "Name", live at "Address" and their phone
number is p h o n e and their age is age?
> I want to put all the names in the names array, all the address in
> address array all the phone in the phone array etc
my $filename = "textfileinasinglecolumnwhichhasetc.txt";
my $state = 0;
my(@names, @address, @phone, @age);
open(FILE, $filename) or die "Can't open '$filename': $!";
while (my $line = <FILE>) {
chomp($line);
SWITCH: {
$state == 0 && do { push @names, $line; last SWITCH; };
$state == 1 && do { push @address, $line;last SWITCH; };
$state == 2 && do { push @phone, $line; last SWITCH; };
$state == 3 && do { push @age, $line; last SWITCH; };
};
$state++;
$state = 0 if $state == 4;
}
close(FILE) or die "Can't close '$filename': $!";
Not tested.
probably a better way to store data like this would be to use an array
of arrays. Or even better an array of hashes. But I don't know what you
are going to do with it :-).
Notice it doesn't check anything. Normally I would read a line, validate
it and store if it is what I expected and change the state.
I expect much nicer, probably more perlish ways to do it :-)
Note I focussed on readability ;-).
--
Kind regards, feel free to mail: mail(at)johnbokma.com (or reply)
virtual home: http://johnbokma.com/ ICQ: 218175426
John web site hints: http://johnbokma.com/websitedesign/
------------------------------
Date: Mon, 8 Sep 2003 19:20:51 -0700
From: Keith Keller <kkeller-usenet@wombat.san-francisco.ca.us>
Subject: Re: Perl Arguements
Message-Id: <3edjjb.edi.ln@goaway.wombat.san-francisco.ca.us>
-----BEGIN xxx SIGNED MESSAGE-----
Hash: SHA1
On 2003-09-08, Michael P. Broida <michael.p.broida@boeing.com> wrote:
>
> Do you have the "shebang" line at the beginning?
> #!/usr/bin/perl
>
> I'm thinking that if you DON'T have that line and you
> run it without specifying "perl", then it's running
> as commands to a shell (not executing "perl") which
> -might- output what you see.
My shell, bash, says "print: command not found" or some such.
> (Or maybe not; it's just a thought. I'm on Win32, so
> can't test this theory.)
Why not? Doesn't Win32 have a command shell?
- --keith
- --
kkeller-mmmspam@wombat.san-francisco.ca.us
(try just my userid to email me)
AOLSFAQ=http://wombat.san-francisco.ca.us/cgi-bin/fom
-----BEGIN xxx SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org
iEYEARECAAYFAj9dOQIACgkQhVcNCxZ5ID+m3ACfVtGQzjZ6IHJ5splaDuHNyKG4
lg0AnA0gf0WXJOFYzQ5LAid07XQYfSZL
=qpKN
-----END PGP SIGNATURE-----
------------------------------
Date: 9 Sep 2003 02:40:55 GMT
From: sholden@flexal.cs.usyd.edu.au (Sam Holden)
Subject: Re: Perl Arguements
Message-Id: <slrnblqfdn.7s9.sholden@flexal.cs.usyd.edu.au>
On Mon, 8 Sep 2003 19:20:51 -0700,
Keith Keller <kkeller-usenet@wombat.san-francisco.ca.us> wrote:
>
> On 2003-09-08, Michael P. Broida <michael.p.broida@boeing.com> wrote:
>>
>> Do you have the "shebang" line at the beginning?
>> #!/usr/bin/perl
>>
>> I'm thinking that if you DON'T have that line and you
>> run it without specifying "perl", then it's running
>> as commands to a shell (not executing "perl") which
>> -might- output what you see.
>
> My shell, bash, says "print: command not found" or some such.
Korn shell has a print command, and it is a reasonably popular shell.
It does say "-might-" after all.
>
>> (Or maybe not; it's just a thought. I'm on Win32, so
>> can't test this theory.)
>
> Why not? Doesn't Win32 have a command shell?
Not one that will execute files with arbitrary names. And clearly testing
such a thing would be pointless since the OP isn't using the a windows
command shell (since it won't produce the behaviour described).
--
Sam Holden
------------------------------
Date: Tue, 09 Sep 2003 04:43:19 +0200
From: John Bokma <postmaster@castleamber.com>
Subject: Re: Perl Arguements
Message-Id: <1063075504.317874@halkan.kabelfoon.nl>
Keith Keller wrote:
> On 2003-09-08, Michael P. Broida <michael.p.broida@boeing.com> wrote:
[snip]
>> (Or maybe not; it's just a thought. I'm on Win32, so
>> can't test this theory.)
>
>
> Why not? Doesn't Win32 have a command shell?
It has, but .pl is associated with perl so even without the she bang a
.pl script is executed as perl.
without an extension:
(1)
D:\Snippets>arg hello world
'arg' is not recognized as an internal or external command,
operable program or batch file.
and with .bat (silly)
(2)
D:\Snippets>arg hello world
D:\Snippets>print join("\n", @ARGV), "\n";
Can't find file join(\n,
Can't find file @ARGV),
Can't find file \n;
With a proper she-bang and without an extension associated with perl.exe
I expect (1).
And for those who really want the same experience on Windows:
http://www.cygwin.com/
> - --keith
>
> - --
^ please use the appropriate sig separator which is -- followed by one
space. This means that most news readers automatically can remove the 12
(not counting the sig sep) lines which includes the PGP signature. Thanks.
--
Kind regards, feel free to mail: mail(at)johnbokma.com (or reply)
virtual home: http://johnbokma.com/ ICQ: 218175426
John web site hints: http://johnbokma.com/websitedesign/
------------------------------
Date: 8 Sep 2003 18:27:50 -0700
From: tom@ztml.com (Tom)
Subject: Re: Problem with simple contact script.
Message-Id: <59b4279a.0309081727.2ac8e787@posting.google.com>
tadmc@augustmail.com (Tad McClellan) wrote in message news:<slrnblpvn3.jjh.tadmc@magna.augustmail.com>...
.
.
> > I hope this will meet your approval
>
>
> Nope.
>
> 1) It will not compile (a prerequisite of approval).
>
> 2) It will function as a mail relay to any address in the whole wide world!
.
.
All right, one more time...
#!/usr/bin/perl
use strict;
use Mail::Sendmail;
use CGI qw(:standard);
print header("text/html");
my $towhom = param("towhom");
my $name = param("name");
my $email = param("email");
my $comments = param("comments");
my %towhoms = (
loanofficer => 'loanofficer@mortgage-pros.com',
marketing => 'marketing@mortgage-pros.com',
broker => 'broker@mortgage-pros.com',
);
my $safe_towhom = $towhoms{$towhom};
if(!$safe_towhom)
{
print start_html("ERROR"),
p("Sorry, your message was not sent because $towhom is not in our mailing list.");
}
else
{
my %mail = (
To => $safe_towhom,
From => $email,
Subject => $name,
Message => $comments,
);
sendmail(%mail) or die $!;
print start_html("Sendmail"),
p("Thank you, your message has been sent to $towhom.");
}
print end_html;
-------------------------------
If this does not meet your approval, next stop... PERL 101 :(
Tom
ztml.com
------------------------------
Date: Tue, 09 Sep 2003 04:34:14 +0200
From: John Bokma <postmaster@castleamber.com>
Subject: Re: Problem with simple contact script.
Message-Id: <1063074959.321865@halkan.kabelfoon.nl>
PERL 101
Tom wrote:
> tadmc@augustmail.com (Tad McClellan) wrote in message news:<slrnblpvn3.jjh.tadmc@magna.augustmail.com>...
> .
> .
>
>>>I hope this will meet your approval
>>
>>
>>Nope.
>>
>>1) It will not compile (a prerequisite of approval).
>>
>>2) It will function as a mail relay to any address in the whole wide world!
>
> .
> .
>
> All right, one more time...
>
> #!/usr/bin/perl
add -wT
> use strict;
> use Mail::Sendmail;
> use CGI qw(:standard);
>
> print header("text/html");
I don't know if this outputs XHTML and how which header it spits out to
a browser that wants XML.
[snip]
> if(!$safe_towhom)
shouldn't that be a test for definedness?
unless (defined $safe_towhom) {
Also I recommend using unless instead of !
IMHO it makes code more readable
> {
> print start_html("ERROR"),
> p("Sorry, your message was not sent because $towhom is not in our mailing list.");
why not end_html here as well and exit; ?
> }
so you can remove the else and { } which, again IMHO makes the code more
readable.
Also, it is the main (or normal) flow of your program. The unless
defined handles a special case, an exception.
> print start_html("Sendmail"),
> p("Thank you, your message has been sent to $towhom.");
> }
> print end_html;
so the end_html could be put together with the print start_ ...
--
Kind regards, feel free to mail: mail(at)johnbokma.com (or reply)
virtual home: http://johnbokma.com/ ICQ: 218175426
John web site hints: http://johnbokma.com/websitedesign/
------------------------------
Date: Tue, 09 Sep 2003 03:02:04 GMT
From: Bob Walton <bwalton@rochester.rr.com>
Subject: Re: Quotes and circular references
Message-Id: <3F5D41EF.5060601@rochester.rr.com>
JR wrote:
> Hi. I came across an interesting situation today when quoting a
> circular reference. For some reason, when I quoted the circular
> reference $a, in the below script, and within the "h2" hash key for an
> anonymous array, the output was different than when the circular
> reference wasn't quoted (the output included HASH(0x1abf070) when the
> circular reference was quoted, and the actual data when it wasn't).
Well, I'm having a bit of trouble understanding precisely what you mean
when you say "when the circular referenece was quoted". A string like
"HASH(0x1abf070)" is the sort of thing one gets when one stringifies an
unblessed hash reference. Placing a hash reference in a double-quoted
string will force a stringification. So it is not surprising that you
would get the stringification when quoting a hash reference. This has
nothing to do with circular references. If you are doing something akin to:
$z = "$hashref";
then $z will have something like the string HASH(0x...) as its value.
...
> JR
...
--
Bob Walton
------------------------------
Date: Tue, 09 Sep 2003 03:19:46 GMT
From: Stefan Weiss <spaceman-a299c-20030925@ausgehaucht.sensenmann.at>
Subject: Threads troubles
Message-Id: <7235859.cRfcf4FlaW@weyoun.foo.at>
Hi,
I am trying to write a multiuser server (for games, chat, etc) in Perl.
In time, this program might have to service >500 users simultaneously,
who would be connected for some time. So I thought about using threads
instead of forking a new process for every user, in order to keep my
process table healthy and minimize inter-process communication overhead.
I wrote simple server and client scripts to test the theory, but it
does not work at all like I expected. The scripts are short enough,
and I have cut away any unnecessary parts, so I included them both at
the end of this posting.
First problem - threads seem to be working fine, but when I look at the
output of ps, there are still seperate processes for each connection.
Shouldn't the threads all be contained in one large process? I'm using
an ithreads-enabled current version of Perl with Linux 2.4.19.
Second problem - the process (group) just grows and grows with every
connection, and no memory seems to be released after a client
disconnects. I am aware that perl usually does not return freed memory
to the system, but I was hoping that the memory would at least be
reused for the next connection. This is what it looks like:
PID %CPU %MEM VSZ RSS TTY COMMAND
4176 1.3 1.2 4924 3168 pts/6 | | \_ perl svr_thr_x.pl
(server started, no connections yet)
4176 1.0 1.7 8288 4436 pts/6 | | \_ perl svr_thr_x.pl
4182 0.0 1.7 8288 4436 pts/6 | | \_ perl svr_thr_x.pl
4183 0.0 1.7 8288 4436 pts/6 | | \_ perl svr_thr_x.pl
(first client)
4176 1.0 2.0 11384 5356 pts/6 | | \_ perl svr_thr_x.pl
4182 0.0 2.0 11384 5356 pts/6 | | \_ perl svr_thr_x.pl
4183 0.0 2.0 11384 5356 pts/6 | | \_ perl svr_thr_x.pl
4187 0.0 2.0 11384 5356 pts/6 | | \_ perl svr_thr_x.pl
(first client + second client)
4176 0.6 2.0 11368 5348 pts/6 | | \_ perl svr_thr_x.pl
4182 0.0 2.0 11368 5348 pts/6 | | \_ perl svr_thr_x.pl
(both clients disconnected)
4176 0.5 2.4 14440 6244 pts/6 | | \_ perl svr_thr_x.pl
4182 0.0 2.4 14440 6244 pts/6 | | \_ perl svr_thr_x.pl
4193 0.0 2.4 14440 6244 pts/6 | | \_ perl svr_thr_x.pl
(third client)
Third problem - I have absolutely no idea why, but when I run the
client script in another terminal (or on another host even), and hit
Ctrl-C while the client is still receiving data from the server, the
server(!) will quit (and the client too, of course).
Can anybody explain to me what is happening? Is there a better approach
than using threads? Should I just fork away for each new client?
Thanks a lot in advance,
stefan
===[ file svr_thr_x.pl ]==================================================
#!/usr/bin/perl
use strict;
use warnings;
use threads qw(yield);
use threads::shared;
use Socket;
use POSIX qw(strftime);
use IO::Handle;
use constant EOL => "\015\012";
# configuration
my $SVR_NAME = "XXXXXXX v0.001"; # name string
my $SVR_ADDR = undef; # set to undef for INADDR_ANY
my $SVR_PORT = 4887; # default port is 4887
my $MAXCLIENTS = 100; # SOMAXCONN for system max
# listen on SVR_ADDR:SVR_PORT
$SVR_ADDR = $SVR_ADDR ? inet_aton($SVR_ADDR) : INADDR_ANY;
socket(SERVER, PF_INET, SOCK_STREAM, getprotobyname("tcp"))
or die "Error opening socket: $!\n";
setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))
or die "Error trying to set socket reusable option: $!\n";
bind(SERVER, pack_sockaddr_in($SVR_PORT, $SVR_ADDR))
or die "Error on bind: $!\n";
listen(SERVER, $MAXCLIENTS)
or die "Error on listen: $!\n";
print "$SVR_NAME server running on port $SVR_PORT\n";
# main loop
my $curr_client_id = 0;
for (;;) {
my $cl_id = sprintf "CLIENT_%010d", $curr_client_id++;
my $cl_sock = accept(my $client, SERVER);
threads->create("serve_client", $client, $cl_id, $cl_sock);
}
# spawned threads use this sub
sub serve_client {
my ($client, $cl_id, $cl_sock) = @_;
my ($cl_port, $cl_addr) = unpack_sockaddr_in($cl_sock);
my $cl_name = gethostbyaddr($cl_addr, AF_INET);
print "connection from $cl_name:$cl_port [", inet_ntoa($cl_addr), "]\n";
autoflush $client 1;
for (1 .. 10) {
print $client "... talking to $cl_name [id $cl_id] ...", EOL;
sleep 1;
}
close $client;
threads->self->join;
}
===[ file client_x.pl ]===================================================
#!/usr/bin/perl
use strict;
use warnings;
use Socket;
my $host = "localhost";
my $port = 4887;
my $svr_sock = sockaddr_in($port, inet_aton($host));
socket(SERVER, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
connect(SERVER, $svr_sock) or die "Error - could not connect: $!";
while (defined(my $line = <SERVER>)) {
print $line;
}
close (SERVER);
------------------------------
Date: 9 Sep 2003 03:54:52 GMT
From: sholden@flexal.cs.usyd.edu.au (Sam Holden)
Subject: Re: Threads troubles
Message-Id: <slrnblqjob.909.sholden@flexal.cs.usyd.edu.au>
On Tue, 09 Sep 2003 03:19:46 GMT,
Stefan Weiss <spaceman-a299c-20030925@ausgehaucht.sensenmann.at> wrote:
> Hi,
>
> I am trying to write a multiuser server (for games, chat, etc) in Perl.
> In time, this program might have to service >500 users simultaneously,
> who would be connected for some time. So I thought about using threads
> instead of forking a new process for every user, in order to keep my
> process table healthy and minimize inter-process communication overhead.
[snip]
>
> First problem - threads seem to be working fine, but when I look at the
> output of ps, there are still seperate processes for each connection.
> Shouldn't the threads all be contained in one large process? I'm using
> an ithreads-enabled current version of Perl with Linux 2.4.19.
Threads can show up as different processes. Check you ps documentation or
you kernel documentation for details on how to identify threads (and
I guess the perl docs too?)
[snip second problem of memory usage which I can't help with]
> Third problem - I have absolutely no idea why, but when I run the
> client script in another terminal (or on another host even), and hit
> Ctrl-C while the client is still receiving data from the server, the
> server(!) will quit (and the client too, of course).
That's probably something along of the lines of a SIGPIPE terminating
your process. Catch the signal you are getting when writing to the broken
socket, clean up, and continue.
> Can anybody explain to me what is happening? Is there a better approach
> than using threads? Should I just fork away for each new client?
I know very little about perl threads so I'm not going to try and comment
on the threading stuff.
A third solution, to forking and threading, is to do the multiplexing
yourself using something like select (perldoc -f select). Doing
that can often be simpler for things like chat servers where the
connections are not independant (data read from one will be sent to
others, common data will be updated, etc) since all the data is
shared and there are no race conditions or locking issues (since there's
only one 'thread' executing).
--
Sam Holden
------------------------------
Date: Sat, 19 Jul 2003 01:59:56 GMT
From: Bob Walton <bwalton@rochester.rr.com>
Subject: Re:
Message-Id: <3F18A600.3040306@rochester.rr.com>
Ron wrote:
> Tried this code get a server 500 error.
>
> Anyone know what's wrong with it?
>
> if $DayName eq "Select a Day" or $RouteName eq "Select A Route") {
(---^
> dienice("Please use the back button on your browser to fill out the Day
> & Route fields.");
> }
...
> Ron
...
--
Bob Walton
------------------------------
Date: 6 Apr 2001 21:33:47 GMT (Last modified)
From: Perl-Users-Request@ruby.oce.orst.edu (Perl-Users-Digest Admin)
Subject: Digest Administrivia (Last modified: 6 Apr 01)
Message-Id: <null>
Administrivia:
The Perl-Users Digest is a retransmission of the USENET newsgroup
comp.lang.perl.misc. For subscription or unsubscription requests, send
the single line:
subscribe perl-users
or:
unsubscribe perl-users
to almanac@ruby.oce.orst.edu.
To submit articles to comp.lang.perl.announce, send your article to
clpa@perl.com.
To request back copies (available for a week or so), send your request
to almanac@ruby.oce.orst.edu with the command "send perl-users x.y",
where x is the volume number and y is the issue number.
For other requests pertaining to the digest, send mail to
perl-users-request@ruby.oce.orst.edu. Do not waste your time or mine
sending perl questions to the -request address, I don't have time to
answer them even if I did know the answer.
------------------------------
End of Perl-Users Digest V10 Issue 5467
***************************************