Two simple fork Problems

Source: Internet
Author: User
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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.