socket and fork

L

Larry

Hello everybody,

I don't know if this has been covered before, I'd love to code a
tiny server that can hanlde several requests at the same...the following
chuck of code can only handle one connection at a time:

use Socket qw:)DEFAULT :crlf);

$socket = IO::Socket::INET->new() || die "unableto listen";
$socket->listen();

$| = 1;

while (1)
{
$client = $socket->accept;

if ($client)
{
...get data...send response...
close $client;
}

}

How can I go about using fork() ? it's just a tiny server so a couple of
connections at the same time would be good...

thanks
 
M

Martijn Lievaart

Hello everybody,

I don't know if this has been covered before, I'd love to code a
tiny server that can hanlde several requests at the same...the following
chuck of code can only handle one connection at a time: (snip)
How can I go about using fork() ? it's just a tiny server so a couple of
connections at the same time would be good...

Did you look at perldoc perlipc? It's right in there.

HTH,
M4
 
L

Larry

Martijn Lievaart said:
Did you look at perldoc perlipc? It's right in there.

well, that's what I was looking for, still I have some difficulties
figuring out how fork() works. this is what I've got:

use POSIX ":sys_wait_h";

sub REAP {

1 until (-1 == waitpid(-1, WNOHANG));
$SIG{CHLD} = \&REAP;

}

$SIG{CHLD} = \&REAP;

die "can't fork: $!" unless defined( $pid = fork() );

if ($pid) {

# the if{} block runs only in the parent process

waitpid( $pid,0 );

} else {

# the else{} block runs only in the child process
exit(0)

}

how can I merge it with the following?

use Socket qw:)DEFAULT :crlf);

$socket = IO::Socket::INET->new() || die "unableto listen";
$socket->listen();

$| = 1;

while (1)
{
$client = $socket->accept;

if ($client)
{
...get data...send response...
close $client;
}

}


thanks
 
M

Martijn Lievaart

well, that's what I was looking for, still I have some difficulties
figuring out how fork() works. this is what I've got:

Read the part that starts with "And here’s a multithreaded version".
It's exactly what you want.

M4
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top