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
signature.asc
Description: This is a digitally signed message part
/* PLUG: http://plug.org, #utah on irc.freenode.net Unsubscribe: http://plug.org/mailman/options/plug Don't fear the penguin. */
