-bind actual socket programming problems occupied port

https://www.cnblogs.com/rockyching2009/p/11032230.html

One, background

A problem-end communication exists is: how uniquely identifies the main communication. For the socket, to solve this problem is to quad: own IP, its own port, the other IP, the other port.

In socket programming, as Client, the port number is allocated and managed by the operating system, so the case does not exist occupied ports. If, as a server, when bind a port, more or less met the following error:

bind: Address already in use

When the process terminates abnormally or restart network services, the situation is very common problems mentioned above; and as a server process back on track and need, this issue is especially important.

 

Second, the causes of and solutions

/** From APUE */
int initserver(int type, const struct sockaddr *addr, socklen_t alen)
{
	int fd;
	if ((fd = socket(addr->sa_family, SOCK_STREAM, 0)) < 0) {
		perror("socket");
		return (-1);
	}

	if (bind(fd, addr, alen) < 0) {
		perror("bind");
		goto errout;
	}

	if (listen(fd, SOMAXCONN) < 0) {
		perror("listen");
		goto errout;
	}

	return (fd);

errout:
	err = errno;
	close(fd);
	errno = err;
	return(-1);
}

The above code segment, the process terminates immediately put into operation, it would have said the problem begins. That book also has mentioned in APUE:

Normally, the implementation of TCP will prevent us from binding the same address until a timeout expires, which is usually on the order of several minutes.

It also provides a workaround to set the socket SO_REUSEADDR property:

int reuse = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int);

 

However, if your process calls fork () or system () function, the above program is powerless.

We know that each has a file descriptor reference count, increased open time, reducing the close of time, only the reference count reaches zero, file descriptors occupied resources will be recycled. The child process will create a file descriptor reference count increases, so even if the parent process terminates, it will be because the listening socket is not and can not release the reference count is 0, then the corresponding port has been in Listen state (netstat command), resulting in process You can not bind the designated port.

 

Know the reason, the right medicine to: prohibit copy of the file descriptor when you create a child process.

 

Guess you like

Origin www.cnblogs.com/rockyching2009/p/11032230.html