1,
Pid_t PID;
Int listenfd, connfd;
Listenfd = socket (...);
BIND (...);
Listen (...);
While (1)
{
Connfd = accept (....);
If (pid = fork () = 0)
{
// Why Should listenfd be disabled for the derived self-process? If it is disabled, the parent process cannot be reused.
Close (listenfd );
Doit (connfd );
Close (connfd );
Exit (0)
}
Close (connfd );
}
2,
If fork is executed repeatedly, will the code above fork be executed repeatedly? If yes, what should I do if an error occurs? Or does fork copy the current process and continue to execute it?
Q1: UNIX files have a reference count. Reference count: it is a reference currently opened. The number of descriptive words in this file or set of interfaces. After accept is returned, the count of the file table items associated with connfd is 1. After fork is returned, the two descriptive words are shared between parent and child processes, therefore, the reference count value associated with the two sockets is reduced from 2 to 1. This interface is used to clear and release resources until the reference value is 0. (UNIX Network Programming P97)
Q2 and fork are executed downward from the current position.