The fork paradym: Most servers do not have a loop where they get a request, handle the request, and then loop back to the begining. The problem with this paradym is that while the server is "handling the request" no other client can access the server. Instead, most all servers use the following loop:
while (!finished) fd = accept(socket, ...) pid = fork(); if (pid == 0) { close(socket); // close child's copy of the socket handle_request(fd); exit(0); // a normal exit. REQUIRED!!!!!! } else if (pid == -1) { // error. No forking. Bad } else { close(fd); // close parent's copy of the fd to the client } }
The fork system call: Fork is a very weird system call. It is the only system call that returns TWICE every time you call it!
When you call fork, your program is cloned. At the end of fork, there are TWO copies of your program. The first copy is called the parent. It keeps the original process-id. Fork for this copy of the program returns the pid of the child. The second copy of the program is called the child. This copy gets a new process-id (the one returned to the parent). For this copy, fork() returns zero.
You can tell the parent from the child because the parent gets a non-zero return from fork, and the child gets a zero.
After a fork, both copies have the same file descriptors open. Any new file descriptors are not shared, however.
The Fork BOMB : If your program is buggy, it might go into an infinite loop. If this loop contains a fork(), then it will clone itself infinite times. It only takes a few infinite loops to bring down the whole system. Just a 0.1 seconds worth of forking will fire off hundreds of infinite loops. The computer will become so bogged down it doesn't notice you pressing ^C. The server will need to be rebooted, and I'll need to yell at you. So don't do that.