accept() returns the same socket descriptor

1040阅读 0评论2015-12-19 ztguang
分类:C/C++



Is there possible that accept() (on redhat Enterprise 4/linux kernel 2.6) return a same socket value for different tcp connections from the same process of a same application and same machine?

I am so surprised that when I got such a result that many connections have the same socket value on server side when I checked the log file!! How is it possible?!!

By the way, I am using TCP blocking socket to listen.


点击(此处)折叠或打开

  1. main(){
  2.         int fd, clientfd, len, clientlen;
  3.         sockaddr_in address, clientaddress;

  4.         fd = socket(PF_INET, SOCK_STREAM, 0);
  5.         ....
  6.         memset(&address, 0, sizeof address);

  7.         address.sin_address = AF_INET;
  8.         address.sin_port = htons(port);
  9.         ....
  10.         bind(fd, &address, sizeof address);
  11.         listen(fd, 100);
  12.         do {
  13.              clientfd = accept(fd, &clientaddress, &clientlen);

  14.              if (clientfd < 0) {
  15.              ....
  16.              }

  17.              printf("clientfd = %d", clientfd);

  18.              switch(fork()){
  19.              case 0:

  20.                     //do something else
  21.                     exit(0);
  22.              default:
  23.                      ...
  24.              }


  25.           } while(1);
  26.     }
my question is that why printf("clientfd = %d"); prints a same number for different connections!!!

Answers

If server runs in multiple processes (like Apache with mpm worker model), then every process has its own file descriptor numbering starting from 0.

In other words, it is quite possible that different processes will get exact same socket file descriptor number. However, fd number it does not really mean anything. They still refer to different underlying objects, and different local TCP ports.








上一篇:C/S—心跳检测—heartbeat
下一篇:如何判断SOCKET已经断开