andy7t has asked for the wisdom of the Perl Monks concerning the following question:
Considered: etcshadow "do we still hate one-word titles"
Unconsidered by castaway: Keep/Edit/Delete: 11/22/0 - not a useful consideration
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Forking
by etcshadow (Priest) on Jan 04, 2005 at 21:22 UTC | |
| [reply] [d/l] [select] |
by andy7t (Initiate) on Jan 05, 2005 at 21:50 UTC | |
That works great! But there is one small problem. A quick run down of what i'm doing. I've created a simple webserver (mainly because Apache can't execute root commands, but thats another story). So, i have this:
#START MY LISTENING DAEMON WITH HTTP::DAEMON
# Fork to begin with so that it can run from
# shell in the background
my $mainpid = fork;
if(!$mainpid)
{
while ($new_sock = $sock->accept()) {
# Theres a connection, fork it so that that user
# has there own dedicated process
my $pid = fork;
if(!$pid)
{
while (my $request_obj = $new_sock->get_request()) {
#This is a new HTTP header, and is basically a
#request for a page
#Fork again
my $pid2 = fork;
if(!$pid2) {
#RETURN THE PAGE
exit; #This kill $pid
}
} #End reading the object
exit; #Kill the child
}#End Fork2
} #End Accept Request
} # End the main fork
This code works fine. The problem is, it leaves behind lots of these: root 5066 0.0 0.0 0 0 pts/1 Z 21:33 0:00 perl <defunct> What's causing it? | [reply] |
by etcshadow (Priest) on Jan 06, 2005 at 02:49 UTC | |
Anyway, it's really easy to deal with this in perl... you just add this line to the top of your script:
Now, as for writing your own web server... to do this as a learning exercise is cool and all, but I think you'd really be much better off using an already existing one (such as apache) for real use. It's easier to work around the problems of not being able to run the web server as root (which you really shouldn't be doing! there's a good reason apache wants you to setuid to an unpriveleged user!) than to work out all of the stuff that apache can do for you. That all being said, though, here's a simple web server that I once wrote (as a learning exercise)... just to give you some more example code. I'm not claiming it to be super good or secure or anything... but it is a good example of forking in practice. I think it borrows pretty heavily from an example in the Perl Cookbook (which you might want to get a copy of).
Enjoy!
| [reply] [d/l] [select] |