Doh! Stupid Programming Mistakes <humor>
Corey Edwards
tensai at zmonkey.org
Thu Oct 19 12:45:48 MDT 2006
On Thu, 2006-10-19 at 12:39 -0600, Alex Esplin wrote:
> This is going to show my inexperience in a big way, but I might as
> well take the chance to learn some more today.
>
> Now that I know what fork() does, what kind of situations would you
> want to use it in? I can see this as being really useful, but I don't
> quite have my head wrapped around it yet.
One very common use is when writing a network server. The default (and
easiest) way to use sockets is with blocking calls. That means that you
make a call to read data from the network and the OS blocks further
execution until more data is ready. That's fine if you only want one
client, but hardly a solution. So instead you fork off a child for each
connection.
socket();
while (accept()){
if (!fork()){
/* child handles this connection */
return 0;
}
else{
/* parent just carries on and waits for the next one */
}
}
At a certain point this becomes unwieldy, so they creating non-blocking
sockets where you can have a single process check to see if data is
available. If it's not, the call returns immediately saying so and you
carry on. It takes a different coding paradigm, but can scale much
further.
Corey
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 191 bytes
Desc: This is a digitally signed message part
Url : http://plug.org/pipermail/plug/attachments/20061019/7f9666ab/attachment.pgp
More information about the PLUG
mailing list